Workshop › Space Invaders-style › Step 9 of 21

The march

What we are doing

The invaders march together in steps: 10 pixels sideways every half second. When the formation would pass an edge, it steps down 16 pixels instead and turns around.

```js
let dir = 1 // +1 marching right, -1 marching left
let lastStep = 0

function stepInterval() {
  return 500
}

function march() {
  const living = alive()
  const left = Math.min(...living.map((invader) => invader.x))
  const right = Math.max(...living.map((invader) => invader.x + invader.w))
  if ((dir > 0 && right + 10 > canvas.width - 10) || (dir < 0 && left - 10 < 10)) {
    for (const invader of living) invader.y += 16
    dir = -dir
  } else {
    for (const invader of living) invader.x += 10 * dir
  }
}

  if (now - lastStep >= stepInterval()) {
    lastStep = now
    march()
  }
```

What it means

Your turn

  1. Under the invader loop, write dir and lastStep.
  2. Under shoot, write stepInterval and march.
  3. At the end of update, take a step when it is time.

Skills: Game states, The game loop

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