Skip to content
Download

2. The ship

  1. In Resources, right-click the objects folder › New object…, named Player.

  2. In the Inspector, under Appearance, pick the sprite nave.

  3. Under Variables, + Variable › number, named velocidade with the value 2 (pixels per step).

  4. Open the room Main and drag Player into it. In the instance Inspector, Position X 160, Y 150.

The room Main with the ship.

Open code, in the object Inspector, opens the file. Replace the contents:

objects/Player.lua
function onSpawn(self)
self.animSpeed = 0.2
end
function onUpdate(self)
local dx = axis("esquerda", "direita")
local dy = axis("cima", "baixo")
if dx ~= 0 and dy ~= 0 then
dx = dx * 0.7071
dy = dy * 0.7071
end
self.x = clamp(self.x + dx * self.velocidade, 8, roomWidth() - 8)
self.y = clamp(self.y + dy * self.velocidade, 8, roomHeight() - 8)
end
  • onSpawn runs once; onUpdate, every step. animSpeed = 0.2 changes frame every 5 steps.
  • axis returns -1 to 1 for a pair of actions. esquerda, direita, cima and baixo come with the project, bound to the arrows, WASD and the gamepad.
  • The 0.7071 factor evens out the diagonal speed; clamp keeps the ship inside the room.
  • velocidade is the Inspector variable.

Play (F5). The ship moves with the arrows or WASD. Change velocidade in the Inspector to see the effect, without touching the code.

Next part: 3. Shots