Build a Platformer with Love2D

The Game Loop

15 min+30 XP

The Game Loop

Every game runs in a loop that continuously updates and renders the game state. Understanding this loop is fundamental to game development.

How Games Work

A game loop typically does three things every frame:

  1. Process input - Check for keyboard/mouse input
  2. Update - Move objects, check collisions, update game state
  3. Draw - Render everything to the screen

This happens 60 times per second (or more), creating the illusion of movement.

Delta Time (dt)

The love.update(dt) function receives a parameter called dt (delta time). This is the time in seconds since the last frame.

Why is this important?

If we move our player by a fixed amount each frame, the game runs differently on fast vs slow computers. Using dt makes movement consistent:

lua
-- Bad: Speed depends on framerate x = x + 5 -- Good: Speed is consistent regardless of framerate x = x + speed * dt

Practical Example

Let's create a simple animation using the game loop. We'll make a circle move across the screen:

lua
function love.load() -- Starting position x = 0 y = 150 speed = 100 -- pixels per second end function love.update(dt) -- Move right by speed * dt pixels x = x + speed * dt -- Wrap around when we go off screen if x > 400 then x = -20 end end function love.draw() -- Draw a white circle at (x, y) love.graphics.setColor(1, 1, 1) love.graphics.circle("fill", x, y, 20) end

Key Concepts:

  • love.graphics.setColor(r, g, b) sets the drawing color (values from 0 to 1)
  • love.graphics.circle("fill", x, y, radius) draws a filled circle
  • dt ensures smooth, consistent movement

Try it! Watch the circle move across the screen. Try changing the speed value!

Ready to experiment?

Open the sandbox to modify and run the code yourself.