Lesson 4 of 22, in world 1: Foundations
Coordinates & Transforms
Every object in a 2D game has a position on screen. Before you can move anything you need to know how that space is laid out — and how to place, turn and size objects in it with transforms.
Screen space
The canvas (or game window) is a grid of pixels. The origin (0, 0) is in the top-left corner; x increases to the right and y increases downward. So “jump up” means decreasing y — a classic beginner gotcha.
Move your mouse around. x grows to the right, y grows DOWN — the opposite of the maths graphs you drew at school.
Drawing things
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'black'
ctx.fillRect(0, 0, canvas.width, canvas.height) // clear the frame
ctx.fillStyle = 'cyan'
ctx.fillRect(player.x, player.y, 32, 32) // a 32×32 square at the player's positionLocal space and transforms
You don’t want to recompute every vertex of a spaceship each time it moves or turns. Instead you describe the ship once in its own local space — centred on (0,0), pointing along +x — and apply a transform: translate (move), rotate (turn) and scale (resize). The transform maps local coordinates to world coordinates.
The ship is drawn once, in its own local space around (0,0), pointing right. The transform moves that local space into the world. Switch the order to see that "rotate then move" is not the same as "move then rotate".
ctx.save() // remember the current transform
ctx.translate(ship.x, ship.y) // move the origin to the ship
ctx.rotate(ship.angle) // turn the axes
ctx.scale(ship.size, ship.size)
drawShipAtOrigin(ctx) // draw as if the ship were at (0,0) pointing right
ctx.restore() // back to the previous transformPivot (origin) point
Objects rotate and scale around their local origin. If you define a sprite with its top-left corner at (0,0), it will spin around that corner. That’s why sprites are usually centred on their origin — or, for characters, have the origin at their feet.
Key takeaways
- Screen origin is the top-left; y grows downward.
- Draw objects in their own local space around (0,0), then transform them into the world.
- Transforms are translate, rotate, scale — and the order you apply them matters.
Check yourself
Q1. A character should jump UP. What happens to its y coordinate?
Q2. Why define a sprite centred on (0,0) in local space?
Q3. translate→rotate and rotate→translate give…
Exercises
- In the transform demo, choose "rotate → translate" and move the rotation slider. Describe the path the ship follows. Why does it orbit the top-left corner?
- Set scale to a negative value in your head: what would scale(-1, 1) do to a sprite? (Hint: it is how games flip characters to face left.)