Guides

Timers and Cooldowns

A lot of things in games happen after a while: an enemy that spawns every few seconds, a power-up that wears off, a gun that can only shoot so fast. In MDog Engine, the easiest way to time things is to count ticks. The active function runs 160 times a second, so 160 ticks is one second.

Hold space to shoot. The cannon can only fire every quarter second, and the light in the corner blinks once a second.

Cooldowns

A cooldown is just a number of ticks to wait. When the cannon fires, cooldown gets set to 40, and it goes down by one every tick. You can't fire again until it's back to 0.

Every So Often

ticks goes up by one every tick. ticks % 160 counts from 0 to 159 over and over, so you can make something happen once a second:

if (ticks % 160 === 0) {
    spawnEnemy();
}

The blinking light is the same trick. ticks % 160 < 80 is true for the first half of every second.

Waiting, Then Doing Something

To wait before something happens, count down to it. Here's a power-up that lasts five seconds:

let powerUpTicks = 0;

function collectPowerUp() {
    powerUpTicks = 5 * 160; // Five seconds
}

function main() {
    if (powerUpTicks > 0) {
        powerUpTicks--;
        if (powerUpTicks === 0) {
            // The power-up just ran out
        }
    }
}

Why Not setTimeout()?

JavaScript's setTimeout() waits a number of milliseconds, but it has no idea your game exists. It keeps counting while the game is paused and while the tab is hidden. Counting ticks keeps your timers in step with everything else.