Lesson 6 of 10
The enemy spawner
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
Accumulate time and cap the number of enemies
Explanation
In most games, enemies appear on a timer, with a new one every interval seconds. The simple approach that comes to mind first is if (timer >= interval) { spawn(); timer = 0; }, but it quietly ties how often enemies appear to how fast the device is.
The reason is that resetting to zero throws away the time left over past the interval, and that leftover changes from frame to frame, so the longer your frames take, the fewer enemies you get. The right way is a time accumulator: you add dt to it, then subtract interval instead of resetting it, and keep subtracting as long as timer >= interval. That's why you use while, not if. One long frame after coming back from a hidden tab can hold three intervals, so three enemies should appear in it.
You also need a cap, so there are never more than max enemies at once. Time that passes while the count is full is lost, not saved for later. Otherwise the spawner would release a big wave of enemies the moment a slot opens up.
Your task
Write updateSpawner(spawner, enemies, dt, rng) for a spawner shaped like { timer, interval, max }. Make each new enemy with the ready-made makeEnemy(rng) function, passing it the rng you were given, then add it to enemies.
Checks
6 checks- An enemy appears when the interval is up, not before
- Leftover time isn't lost
- A long frame creates every enemy it missed
- The number of enemies never goes over max
- Time that passes while the count is full isn't saved up
- Enemies are made with makeEnemy and the same rng