Lesson 10 of 10
A camera that follows the player
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
Show a world that's bigger than the screen
Explanation
When the game world is bigger than the screen, what moves is the camera, not the world. The camera is a screen-sized rectangle whose position is given in world coordinates, and everything you draw gets shifted by the opposite of that position: screenX = worldX - camera.x.
To keep the player in the middle of the camera, you write camera.x = player.x - camera.w / 2. Near the edge of the world, though, this shows what lies beyond it, which is empty space with nothing drawn in it. So you clamp the camera's position between 0 and world.w - camera.w: the scrolling stops at the world's edge, and the player keeps going toward the edge of the screen.
Keep the two kinds of coordinates apart in your code. Write all the game logic, from movement and collisions to how enemies behave, in world coordinates, and convert to screen coordinates only at the moment you draw. Mix them up, and you'll see your enemies slide along with the camera every time it moves.
Your task
Write follow(camera, player, world) to position the camera { x, y, w, h } so the player { x, y } is in its center, while keeping it inside the world bounds { w, h }. Then write worldToScreen(x, y, camera) to return the position { x, y } on the screen. The preview draws everything with this function.
Checks
5 checks- The player is in the middle of the camera
- The camera never shows anything before the start of the world
- The camera never shows anything past the end of the world
- worldToScreen subtracts the camera position
- A player the camera follows is in the middle of the screen