3. Shots
In the editor
Section titled “In the editor”-
Create the object
Bullet, with the spritetiro. It does not go in the room: it is created by code. -
In the Layers panel, + Layer › Instances, named
Tiros, belowInstancias. Then clickInstanciasagain. -
In Project › Project settings… › Input actions, + Action named
atirar, bound to the space bar and toPad:A. -
On
Player, create the variableintervaloTiro, of type integer, with the value10(steps between shots).
Bullet
Section titled “Bullet”function onSpawn(self) self.vspeed = -5end
function onUpdate(self) if self.y < -8 then self:destroy() endend#pragma once#include <brasa/brasa.hpp>
class Bullet : public brasa::Entity {public: BRASA_VARS(Bullet)
void onSpawn() override; void onUpdate() override;};#include "Bullet.hpp"
using namespace brasa;
void Bullet::onSpawn() { vspeed = -5.0f; }
void Bullet::onUpdate() { if (y < -8.0f) destroy();}
BRASA_ENTITY(Bullet);A negative vspeed goes up: the engine adds the speed to the position every step. A shot that leaves the screen is destroyed.
On Player, add the “can shoot” flag and, at the end of onUpdate, the shot:
function onSpawn(self) self.animSpeed = 0.2 self.podeAtirar = trueend
function onUpdate(self) -- ... if held("atirar") and self.podeAtirar then spawn("Bullet", self.x, self.y - 8, "Tiros") self.podeAtirar = false self:after(self.intervaloTiro, function() self.podeAtirar = true end) endendprivate: bool canShoot_ = true;void Player::onUpdate() { // ... if (held("atirar") && canShoot_) { spawn<Bullet>(x, y - 8.0f, "Tiros"); canShoot_ = false; after(intervaloTiro, [this] { canShoot_ = true; }); }}spawncreates the shot on theTiroslayer, 8 pixels above the ship.afterallows the next shot afterintervaloTirosteps.- C++:
Player.cppusesBulletwith no#include.
Play. Holding the space bar fires a burst. Change intervaloTiro to 3 or 30.
Next part: 4. Enemies
