Class: RGame::Engine::Timer
- Inherits:
-
Object
- Object
- RGame::Engine::Timer
- Defined in:
- lib/rgame/engine/timer.rb
Overview
A repeating interval timer for periodic events that aren't driven by input — a spawner emitting an enemy every N seconds, a tower's fire rate, a wave clock.
It only accumulates time; the owner decides what each elapsed interval means. That
split lets one primitive serve both styles: "act automatically" (consume every ready
interval) and "stay loaded until conditions allow" (check ready?, but consume
only when actually acting — so a tower with no target keeps its shot ready instead of
wasting it). Pure and allocation-free, so it ticks on the per-frame path.
timer = Engine::Timer.new(0.8)
timer.update(dt)
if timer.ready? # at least one whole interval has passed
timer.consume # deduct it (remainder carries forward, so timing won't drift)
spawn_enemy
end
Instance Attribute Summary collapse
-
#interval ⇒ Object
Returns the value of attribute interval.
Instance Method Summary collapse
-
#consume ⇒ Object
Deduct one interval after acting on a ready timer.
-
#initialize(interval) ⇒ Timer
constructor
A new instance of Timer.
-
#ready? ⇒ Boolean
Has at least one whole interval accumulated since the last consume?.
-
#reset ⇒ Object
Drop any accumulated time — e.g.
-
#update(dt) ⇒ Object
Advance by one timestep.
Constructor Details
#initialize(interval) ⇒ Timer
Returns a new instance of Timer.
23 24 25 26 |
# File 'lib/rgame/engine/timer.rb', line 23 def initialize(interval) @interval = interval @elapsed = 0.0 end |
Instance Attribute Details
#interval ⇒ Object
Returns the value of attribute interval.
21 22 23 |
# File 'lib/rgame/engine/timer.rb', line 21 def interval @interval end |
Instance Method Details
#consume ⇒ Object
Deduct one interval after acting on a ready timer. Carries the remainder forward (rather than zeroing) so a long-running cadence doesn't drift. Returns self.
39 40 41 42 |
# File 'lib/rgame/engine/timer.rb', line 39 def consume @elapsed -= @interval self end |
#ready? ⇒ Boolean
Has at least one whole interval accumulated since the last consume?
35 |
# File 'lib/rgame/engine/timer.rb', line 35 def ready? = @elapsed >= @interval |
#reset ⇒ Object
Drop any accumulated time — e.g. after retuning the interval. Returns self.
45 46 47 48 |
# File 'lib/rgame/engine/timer.rb', line 45 def reset @elapsed = 0.0 self end |
#update(dt) ⇒ Object
Advance by one timestep. Returns self so callers can chain.
29 30 31 32 |
# File 'lib/rgame/engine/timer.rb', line 29 def update(dt) @elapsed += dt self end |