Workshop › Scorched Earth-style Artillery › Step 20 of 23

Aim with the mouse

What we are doing

On a phone there are no arrow keys, so you can aim by pointing: the direction from your barrel to the pointer is the angle, and the distance is the power. Math.atan2 turns a direction into an angle. After the game, a tap plays again.

```js
// Point from your tank: the direction is the aim, the distance is the power.
function pointAt(event) {
  const rect = canvas.getBoundingClientRect()
  const x = ((event.clientX - rect.left) * W) / rect.width
  const y = ((event.clientY - rect.top) * H) / rect.height
  const t = tanks[0]
  const angle = Math.atan2(y - (t.y - 8), x - t.x)
  t.angle = angle
  t.power = Math.max(2, Math.min(MAX_POWER, Math.hypot(x - t.x, y - (t.y - 8)) / 12))
}

canvas.addEventListener('pointerdown', (event) => {
  if (state === 'won' || state === 'lost') return reset()
  if (state !== 'aiming' || turn !== 0) return
  pointAt(event)
})
```

What it means

Your turn

Above draw, write pointAt and the pointer listener.

Skills: Keyboard and mouse input, Velocity and gravity

All steps

  1. The ground
  2. Hills
  3. Two tanks
  4. The barrel
  5. The game loop
  6. Aim
  7. Angle and power
  8. Fire!
  9. Flight
  10. Boom
  11. Craters
  12. Falling tanks
  13. Damage
  14. Taking turns
  15. The computer's shot
  16. Hitting a tank
  17. Win or lose
  18. Wind
  19. The computer aims
  20. Aim with the mouse
  21. Drag and let go
  22. The atan2 trap
  23. Build it yourself: a trail