Workshop › OutRun-style Racer › Step 31 of 44

Cars that shrink with distance

What we are doing

To draw a car, find its segment in shown: its near edge tells where on screen that distance is and how wide the road is there. The car is a third of that width: far cars come out tiny, near ones big. Far cars are drawn first.

```js
// The other cars, far ones first, sized by their distance.
const visible = cars
  .map((car) => ({ car, gap: ahead(position, car.z) }))
  .filter((c) => c.gap > PLAYER_Z * 0.5 && c.gap < DRAW * SEG)
  .sort((a, b) => b.gap - a.gap)
for (const { car } of visible) {
  const seg = shown.find((s) => s.index === Math.floor(car.z / SEG) % segments.length)
  if (!seg) continue
  const w = seg.near.w * 0.35
  ctx.fillStyle = '#facc15'
  ctx.fillRect(seg.near.x + car.x * seg.near.w - w / 2, seg.near.y - w * 0.6, w, w * 0.6)
}
```

What it means

Your turn

In draw, above the // Your car. comment, write the other cars' code followed by an empty line.

Skills: Drawing on a canvas, Arrays and objects

All steps

  1. Sky and ground
  2. Draw again and again
  3. Perspective
  4. One piece of road
  5. A road made of segments
  6. Where we are on the track
  7. The road ahead
  8. Stripes
  9. Paint from far to near
  10. Kerbs and a center line
  11. Striped grass
  12. Moving is one number
  13. Which keys are down?
  14. The gas pedal
  15. Brake, coast and a top speed
  16. Your car
  17. Speedometer
  18. A pedal for phones
  19. Move the camera sideways
  20. Steering
  21. No turning on the spot
  22. The grass is slow
  23. Steering by touch
  24. A track with curves
  25. Bend the road
  26. No jumps in the curve
  27. Which segment am I on?
  28. Curves pull you outwards
  29. Other cars
  30. Distance on a loop
  31. Cars that shrink with distance
  32. Traffic moves
  33. Rear-end crash
  34. Counting laps
  35. Show the lap
  36. A lap timer
  37. Show the time
  38. Best lap
  39. Show the best lap
  40. Racing or finished
  41. The finish line
  42. Finished!
  43. Race again
  44. Build it yourself: beat the clock