Lesson 10 of 10

A camera that follows the player

Goal

Show a world that's bigger than the screen

01

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.

02

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
  1. The player is in the middle of the camera
  2. The camera never shows anything before the start of the world
  3. The camera never shows anything past the end of the world
  4. worldToScreen subtracts the camera position
  5. A player the camera follows is in the middle of the screen
03

Hints

0/3
Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.

index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.

Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.