Gravity & Jumping
Platformers need gravity to pull the player down and jumping to move up. Let's implement both!
How Gravity Works
Gravity is an acceleration - it continuously increases the player's downward velocity:
luavelocity.y = velocity.y + gravity * dt position.y = position.y + velocity.y * dt
Implementing Jump
When the player presses jump, we set an upward velocity. Gravity then pulls them back down:
luaif jump_pressed and on_ground then velocity.y = -jump_force end
The Complete Code
luafunction love.load() player = { x = 50, y = 200, width = 30, height = 40, speed = 200, velocityY = 0, gravity = 800, jumpForce = -400, onGround = false } ground = { y = 250 } end function love.update(dt) -- Horizontal movement if love.keyboard.isDown("left") or love.keyboard.isDown("a") then player.x = player.x - player.speed * dt end if love.keyboard.isDown("right") or love.keyboard.isDown("d") then player.x = player.x + player.speed * dt end -- Apply gravity player.velocityY = player.velocityY + player.gravity * dt -- Update vertical position player.y = player.y + player.velocityY * dt -- Check ground collision if player.y + player.height >= ground.y then player.y = ground.y - player.height player.velocityY = 0 player.onGround = true else player.onGround = false end -- Keep player on screen horizontally 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.keypressed(key) -- Jump when space or W is pressed if (key == "space" or key == "w" or key == "up") and player.onGround then player.velocityY = player.jumpForce player.onGround = false 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, ground.y, 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("SPACE/W/UP to jump, LEFT/RIGHT to move", 10, 10) end
New Concepts:
love.keypressed(key)is called once when a key is pressed (not held)velocityYtracks vertical speed (negative = up, positive = down)onGroundprevents double-jumping
Try it! Press SPACE to jump!