Workshop › Space Invaders-style › Step 9 of 21
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()
}
```left and right are the edges of the living formation (... spreads the list of positions into Math.min).dir flips; otherwise everyone moves sideways.stepInterval is 500 ms for now; it will change later.dir and lastStep.shoot, write stepInterval and march.update, take a step when it is time.Skills: Game states, The game loop