Workshop › Tower Defense › Step 19 of 42
A tower keeps asking: which enemy do I shoot? The classic answer: among those in range, the one that has walked the
furthest, because it is the closest to getting through. With d, "furthest" is just the biggest d.
```js
// The enemy in range that has walked the furthest: it is the closest to getting through.
function targetFor(tower) {
const range = TOWERS[tower.kind].range
let target = null
for (const e of enemies) {
const p = pointAt(e.d)
const inRange = Math.hypot(p.x - tower.col, p.y - tower.row) <= range
if (inRange && (!target || e.d > target.d)) target = e
}
return target
}
```Math.hypot(dx, dy) is the straight distance between two points, in tiles here.target starts as null; an enemy in range replaces it if there is none yet or if it has walked further.null.Above function update() { write the comment and targetFor.
Skills: Collision detection