Skip to content
Download

4. Enemies

  1. Create the object Enemy, with the sprite inimigo. It does not go in the room.

  2. Create the Instances layer Inimigos, below Tiros, and go back to Instancias.

  3. Create the object Spawner, with no sprite, and drag it into the room Main.

objects/Enemy.lua
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() end
end
function kill(self)
if not self:exists() then return end
self:destroy()
end
  • random gives each enemy a fall speed.
  • onCollide runs when a Bullet touches it: the shot is destroyed and the enemy dies.
  • kill is a function of the object itself. The check at the start avoids dying twice on the same step.
objects/Spawner.lua
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

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