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:
- Process input - Check for keyboard/mouse input
- Update - Move objects, check collisions, update game state
- 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:
luafunction 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 circledtensures smooth, consistent movement
Try it! Watch the circle move across the screen. Try changing the speed value!