Build a Platformer with Love2D

Player Movement

20 min+40 XP

Player Movement

Now let's make our player move! We'll read keyboard input and update the player's position.

Reading Keyboard Input

Love2D provides love.keyboard.isDown(key) to check if a key is currently pressed:

lua
if love.keyboard.isDown("left") then -- Left arrow is pressed end if love.keyboard.isDown("a") then -- A key is pressed end

Adding Movement

Let's update our scene to allow the player to move left and right:

lua
function love.load() player = { x = 50, y = 200, width = 30, height = 40, speed = 200 -- pixels per second } end function love.update(dt) -- Move left if love.keyboard.isDown("left") or love.keyboard.isDown("a") then player.x = player.x - player.speed * dt end -- Move right if love.keyboard.isDown("right") or love.keyboard.isDown("d") then player.x = player.x + player.speed * dt end -- Keep player on screen if player.x < 0 then player.x = 0 end if player.x + player.width > 400 then player.x = 400 - player.width end end function love.draw() -- Sky love.graphics.setColor(0.4, 0.7, 1) love.graphics.rectangle("fill", 0, 0, 400, 300) -- Ground love.graphics.setColor(0.4, 0.8, 0.4) love.graphics.rectangle("fill", 0, 250, 400, 50) -- Player love.graphics.setColor(1, 0.3, 0.3) love.graphics.rectangle("fill", player.x, player.y, player.width, player.height) -- Eyes love.graphics.setColor(1, 1, 1) love.graphics.circle("fill", player.x + 10, player.y + 12, 5) love.graphics.circle("fill", player.x + 22, player.y + 12, 5) -- Pupils love.graphics.setColor(0, 0, 0) love.graphics.circle("fill", player.x + 12, player.y + 12, 2) love.graphics.circle("fill", player.x + 24, player.y + 12, 2) -- Instructions love.graphics.setColor(1, 1, 1) love.graphics.print("Use LEFT/RIGHT or A/D to move", 10, 10) end

Key Concepts:

  • We check for both arrow keys AND WASD keys for accessibility
  • player.speed * dt ensures consistent movement speed
  • Boundary checking keeps the player on screen

Try it! Use the arrow keys or A/D to move the player left and right.

Ready to experiment?

Open the sandbox to modify and run the code yourself.