4. Enemies
In the editor
Section titled “In the editor”-
Create the object
Enemy, with the spriteinimigo. It does not go in the room. -
Create the Instances layer
Inimigos, belowTiros, and go back toInstancias. -
Create the object
Spawner, with no sprite, and drag it into the roomMain.
function onSpawn(self) self.animSpeed = 0.1 self.vspeed = random(0.8, 1.6) self:onCollide("Bullet", function(bullet) bullet:destroy() self:kill() end)end
function onUpdate(self) if self.y > roomHeight() + 16 then self:destroy() endend
function kill(self) if not self:exists() then return end self:destroy()end#pragma once#include <brasa/brasa.hpp>
class Enemy : public brasa::Entity {public: BRASA_VARS(Enemy)
void onSpawn() override; void onUpdate() override;
void kill();};#include "Enemy.hpp"
using namespace brasa;
void Enemy::onSpawn() { animSpeed = 0.1f; vspeed = random(0.8f, 1.6f); onCollide<Bullet>([this](Bullet& bullet) { bullet.destroy(); kill(); });}
void Enemy::onUpdate() { if (y > static_cast<float>(roomHeight()) + 16.0f) destroy();}
void Enemy::kill() { if (isDestroyed()) return; destroy();}
BRASA_ENTITY(Enemy);randomgives each enemy a fall speed.onCollideruns when aBullettouches it: the shot is destroyed and the enemy dies.killis a function of the object itself. The check at the start avoids dying twice on the same step.
Spawner
Section titled “Spawner”function onSpawn(self) self.criados = 0 self:agendar()end
function agendar(self) local intervalo = math.max(15, 60 - self.criados * 2) self:after(intervalo, function() self.criados = self.criados + 1 local margem = 16 spawn("Enemy", random(margem, roomWidth() - margem), -16, "Inimigos") self:agendar() end)end#pragma once#include <brasa/brasa.hpp>
class Spawner : public brasa::Entity {public: BRASA_VARS(Spawner)
void onSpawn() override;
private: void scheduleNext(); int spawned_ = 0;};#include "Spawner.hpp"#include <algorithm>
using namespace brasa;
void Spawner::onSpawn() { scheduleNext(); }
void Spawner::scheduleNext() { const int interval = std::max(15, 60 - spawned_ * 2); after(interval, [this] { ++spawned_; const float margin = 16.0f; spawn<Enemy>(random(margin, static_cast<float>(roomWidth()) - margin), -16.0f, "Inimigos"); scheduleNext(); });}
BRASA_ENTITY(Spawner);The interval starts at 60 steps and drops 2 per enemy, down to a minimum of 15. The function spawns an enemy above the screen and schedules itself again.
Play. Enemies fall faster and faster and disappear when shot.
Next part: 5. Score and lives
