Make-Games-With-Love

Enemy Movement

The enemies need to move, so we create a function that we call every update loop.

It has two arguments, the ship itself and the delta time.

local updateEnemy = function(enemyShip, dt)
    enemyShip.y = enemyShip.y + dt * enemyShip.velocity
end

You need to add a row to the enemyShip table in the newEnemy function. local enemyShip = { -- ... draw = drawEnemy, update = updateEnemy }

The ship is just increasing it's Y coordinate. It is moving from the top of the screen to the bottom. We need to add another ipairs loop to the love.update function:

for _, ship in ipairs(enemies) do
    v:update(dt)
end

It can go before our keyboard checks:

function love.update(dt)
    for _, ship in ipairs(enemies) do
         v:update(dt)
     end

    if love.keyboard.isDown("left") then
        ship.x = ship.x - dt * ship.velocity
    elseif love.keyboard.isDown("right") then
        ship.x = ship.x + dt * ship.velocity
    end
    if love.keyboard.isDown("up") then
        ship.y = ship.y - dt * ship.velocity
    elseif love.keyboard.isDown("down") then
        ship.y = ship.y + dt * ship.velocity
    end
end

If We Wrap around

If the enemy gets outside of the screen area we want to set it to the top again. We need to change the updateEnemy function a bit:

local updateEnemy = function(enemyShip, dt)
    enemyShip.y = enemyShip.y + dt * enemyShip.velocity

    if enemyShip.y > love.graphics.getHeight() then
        enemyShip.y = -32
    end
end

The if statement is pretty easy. You begin with a if keyword followed by an expression. When the boolean expression is true the code after the then is executed.

This means that if the y coordinate is higher than the screens width we put the enemyShip back to -32.

Hint: A common mistake is to forget the then and the end! Be careful and always check twice if you have all of your if then end.

Random position

The enemies move in perfect sync. Which is weird. We can change the Y start position to give every enemy a different movement. Lua has a table on board that has a random number generator.

function love.load()
    math.randomseed(os.time())
    newEnemy(200, 50 + math.random(500))
    newEnemy(300, 50 + math.random(500))
    newEnemy(400, 50 + math.random(500))
    newEnemy(500, 50 + math.random(500))
end

We initialize the random number generator with giving it a seed. We can then call the random function and get a number from 1 to 500.

The rectangles should now run at different positions:

rectangular war