Game Dev Advanced

24  Game states

Games are state machines: a screen enum plus rules for legal transitions. Drive the transitions with a match on (state, event), then build the other gamedev staple -- a cooldown timer.

Step 2 / 2

Implement Cooldown::tick: count down by dt; on reaching 0, reset and return true.

Hints
  • Subtract first: self.remaining -= dt; then test <= 0.0.
  • On fire, reset: self.remaining = self.duration; and return true.
24_state_machine.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
struct Cooldown { remaining: f32, duration: f32 }

impl Cooldown {
    fn tick(&mut self, dt: f32) -> bool {
        self.remaining -= dt;
        if self.remaining <= 0.0 {
            self.remaining = self.duration;
            true
        } else {
            false
        }
    }
}