Skip to content

Count down with a timer ​

Goal ​

A HUD meter counts from three seconds to zero, then says “Go”.

Files you will edit ​

  • src/game.ts

Steps ​

  1. In a template such as top-down, use this small game definition for the exercise. Keep the template's host and manifest. Allocate the timer and HUD model once; reset and start the timer on every new game.

    ts
    import { createTimers, defineGame, type GameContext } from 'gameable';
    
    const model = { bars: { seconds: { value: 3, max: 3 } }, message: 'Wait' };
    const timers = createTimers({
      capacity: 1,
      onFire() {
        model.message = 'Go';
      },
    });
    function countdown(ctx: GameContext): void {
      timers.step(ctx);
      model.bars.seconds.value = timers.remaining(0);
      ctx.hud.set(model);
    }
    export default defineGame({
      init(ctx) {
        timers.reset();
        model.message = 'Wait';
        model.bars.seconds.value = 3;
        timers.start(ctx, 0, 3);
      },
      systems: [{ run: countdown, on: 'authority' }],
      snapshot: () => timers.snapshot(),
      restore: (state) => {
        timers.restore(state);
        model.message = timers.active(0) ? 'Wait' : 'Go';
      },
    });
  2. For a repeating timer, pass true as the final start argument. Repeats rearm before onFire; one-shots retain progress 1. A zero duration takes one step. In a room, publish the model through player HUDs or messages.

Verify ​

sh
npm run dev

At 60 Hz the seconds meter reaches zero on step 180 and the message becomes Go once. Reload: the meter starts at three again. Pausing simulation must also pause this countdown.

See also ​