Workshop › OutRun-style Racer › Step 9 of 44
We paint near segments first. Later, curves bend the road behind itself and cars sit on it, so the rule must be: paint the furthest first and the nearest last, so nearer things cover what is behind them (the painter's algorithm). We split the work into two loops: one works out the segments, the other paints them backwards.
```js
const shown = []
for (let i = 0; i < DRAW; i++) {
const index = (base + i) % segments.length
const z = (base + i) * SEG - position
const near = project(0, -CAMERA_HEIGHT, z)
const far = project(0, -CAMERA_HEIGHT, z + SEG)
if (z > 0) shown.push({ index, near, far })
}
// Paint from far to near, so nearer road covers what is behind it.
for (let i = shown.length - 1; i >= 0; i--) {
const { index, near, far } = shown[i]
const light = Math.floor(index / 3) % 2 === 0
quad(light ? '#6b7280' : '#646b75', near.x, near.y, near.w, far.x, far.y, far.w)
}
```{ index, near, far } for each visible segment in shown.i--), so the furthest segment is painted first.const { index, near, far } = shown[i] takes the three fields out of the object into three names.for write const shown = [].light and quad lines and write the shown.push line instead.Skills: Drawing on a canvas, Arrays and objects
← Stripes Kerbs and a center line →