Your First Love2d Game in 200 Lines - Exercises

Posted in Tutorials

Adding Sound Effects

The game is kind of quiet, don't you think? I've included a gunshot sound in the assets zip. Go ahead and add it to the game. You can get some help here:

Like images, sound effects need to be loaded inside our love.load function.

gunSound ="assets/gun-sound.wav", "static")

We then go down into our update, find where the bullets are created and add our play command.

if love.keyboard.isDown(' ', 'rctrl', 'lctrl', 'ctrl') and canShoot then -- Create some bullets newBullet = { x = player.x + (player.img:getWidth()/2), y = player.y, img = bulletImg } table.insert(bullets, newBullet) --NEW LINE gunSound:play() --END NEW canShoot = false canShootTimer = canShootTimerMax end

You might notice that we're not using but instead we use gunSound:play(). This is a Lua language convention. Saying :play is the same as saying .play(gunSound)

Player Vertical Movement

Moving side-to-side is fine, but this isn't the 80s anymore. Long gone are the days of Space Invaders. Let's add vertical movement to our game just like we added horizontal movement. Make sure that we keep our player from flying off-screen.

Add to love.update:

-- Vertical movement if love.keyboard.isDown('up', 'w') then if player.y > ( / 2) then player.y = player.y - (player.speed*dt) end elseif love.keyboard.isDown('down', 's') then if player.y < ( - 55) then player.y = player.y + (player.speed*dt) end end

Display the Score

We're tracking the score, but I seem to have forgotten to display it anywhere. Go ahead and write it out. Remember, we're already writing some text when the game is restarted.

Add to love.draw:, 255, 255)"SCORE: " .. tostring(score), 400, 10)