Workshop › OutRun-style Racer › Step 3 of 44
The heart of the trick is perspective: something twice as far away looks half as big. A point in the world sits
dz in front of the camera, dx to the side and dy above it. project works out where that point lands on the
screen, and how wide the road looks there. Nothing new is drawn yet.
```js
const ROAD = 1000 // half the width of the road
const CAMERA_HEIGHT = 1000
const DEPTH = 1 / Math.tan((50 * Math.PI) / 180) // camera depth for a 100 degree field of view
// Perspective: a point `dz` in front of the camera, `dx` to the side and `dy` above the ground.
function project(dx, dy, dz) {
const scale = DEPTH / dz
return { x: W / 2 + scale * dx * (W / 2), y: H / 2 - scale * dy * (H / 2), w: scale * ROAD * (W / 2) }
}
```ROAD is half the road's width and CAMERA_HEIGHT the camera's height, in world units.DEPTH sets the field of view: Math.tan wants radians, so degrees are multiplied by Math.PI / 180. It is about 0.84.scale = DEPTH / dz is perspective itself: twice the distance, half the scale.x starts from the middle of the screen, y from the horizon (H / 2). The road is below the camera, so dy will
be negative and the point lands below the horizon, closer to it the further away it is.w is half the road's width on screen at that distance. The function returns all three in one object.const H = canvas.height write the three constants.function draw() { write the comment and project, with an empty line between.Skills: Drawing on a canvas, Velocity and gravity
← Draw again and again One piece of road →