Workshop › Tower Defense › Step 7 of 42
How do you move something along a road with corners? Steering it gets messy. Much simpler: give each enemy one
number, d, the distance walked along the road, and write a function that turns a distance into a point.
```js
// Where on the road an enemy is after walking `d` tiles (null once it is past the end).
function pointAt(d) {
for (let i = 1; i < PATH.length; i++) {
const [ax, ay] = PATH[i - 1]
const [bx, by] = PATH[i]
const length = Math.abs(bx - ax) + Math.abs(by - ay)
if (d <= length) return { x: ax + Math.sign(bx - ax) * d, y: ay + Math.sign(by - ay) * d }
d -= length
}
return null
}
```a to corner b is |bx - ax| + |by - ay| tiles long (one of the two is 0).d fits, the point is d tiles from a towards b; Math.sign gives the direction.d -= length, and the next piece is tried. Past the last piece: null.Under reset, after an empty line, write the comment and pointAt.
Skills: Functions
← Draw the road Enemies on the road →