Shoot
You want the player to shoot when a key is pressed. The shot is another object, created on the spot by the code.
Create an object Bullet with the sprite of the shot and this code:
#include <brasa/brasa.hpp>using namespace brasa;
class Bullet : public Entity {public: void onSpawn() override { vspeed = -5.0f; } // goes up 5 pixels per step void onUpdate() override { if (y < -8.0f) destroy(); // left the screen: disappear }};BRASA_ENTITY(Bullet);And in the object that shoots:
void onUpdate() override { if (pressed(Key::Space)) spawn<Bullet>(x, y, "Instancias");}How it works
Section titled “How it works”spawn<Bullet>(x, y, "Instancias")creates a new instance ofBulletat the given position. Here, at the position of whoever shot. The third value is the layer the shot goes into:Instanciasis the one every new room already has.- In the shot’s
onSpawn,vspeed = -5makes it go up by itself: Brasa addshspeed/vspeedto the position on every step. - A shot that leaves the screen is destroyed, so invisible objects don’t pile up.
Variations
Section titled “Variations”Hold to shoot in bursts, with a pause between the shots:
// in the class: bool canShoot_ = true;if (held(Key::Space) && canShoot_) { spawn<Bullet>(x, y, "Instancias"); canShoot_ = false; after(10, [this] { canShoot_ = true; }); // again 10 steps from now}Shoot in any direction. spawn returns the shot it created, so you can change its speed. Vec2::fromAngle(strength, degrees) turns an angle into a speed (0 = right, 90 = up):
if (Bullet* bullet = spawn<Bullet>(x, y, "Instancias")) { const Vec2 v = Vec2::fromAngle(5.0f, angleTo(mouseX(), mouseY())); // towards the mouse bullet->hspeed = v.x; bullet->vspeed = v.y;}The shot’s onSpawn runs inside spawn, so the speed you set afterwards is the one that counts.
