Workshop › Space Invaders-style › Step 3 of 21

Move the ship

What we are doing

While an arrow key is held, the ship slides 4 pixels a frame that way. A keys object remembers which keys are down.

```js
const SHIP_SPEED = 4

const keys = {}

document.addEventListener('keydown', (event) => {
  keys[event.key] = true
})
document.addEventListener('keyup', (event) => {
  keys[event.key] = false
})

function update() {
  if (keys.ArrowLeft) ship.x -= SHIP_SPEED
  if (keys.ArrowRight) ship.x += SHIP_SPEED
}

  update()
```

What it means

Your turn

  1. Under SHIP_H, write SHIP_SPEED.
  2. Under ship, write keys, the two key listeners and update.
  3. In loop, call update() before draw().

Skills: Keyboard and mouse input

All steps

  1. The ship
  2. The game loop
  3. Move the ship
  4. Stay on screen
  5. Fire
  6. Bullets fly
  7. A short reload
  8. The invaders
  9. The march
  10. Hit!
  11. Score
  12. They shoot back
  13. Bombs fall
  14. Lives
  15. Game over
  16. Best score
  17. A wave in a function
  18. Play again
  19. Waves
  20. Faster and faster
  21. Build it yourself: an extra life