feat: add engine/core/interval_timer.go
This commit is contained in:
parent
63a3662dbe
commit
ffbf1332c5
1 changed files with 50 additions and 0 deletions
50
engine/core/interval_timer.go
Normal file
50
engine/core/interval_timer.go
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
package core
|
||||
|
||||
// IntervalTimer tracks elapsed time against a fixed interval and is useful
|
||||
// for triggering recurring events such as animation frame updates, blinking
|
||||
// effects, and periodic AI decisions.
|
||||
//
|
||||
// Unlike a countdown timer, an IntervalTimer accumulates time and signals
|
||||
// when the interval has been reached.
|
||||
type IntervalTimer struct {
|
||||
time float32 // Elapsed time in seconds
|
||||
interval float32 // Interval threshold in seconds
|
||||
}
|
||||
|
||||
// NewIntervalTimer creates a new Timer with the given interval duration.
|
||||
func NewIntervalTimer(interval float32) IntervalTimer {
|
||||
return IntervalTimer{
|
||||
interval: interval,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *IntervalTimer) SetInterval(interval float32) {
|
||||
t.interval = interval
|
||||
}
|
||||
|
||||
// Update advances the timer by dt (delta time in seconds).
|
||||
// Returns true if the accumulated time has reached or exceeded the interval.
|
||||
func (t *IntervalTimer) Update(dt float32) bool {
|
||||
t.time += dt
|
||||
return t.Ticked()
|
||||
}
|
||||
|
||||
// Same as Update, but will also reset the timer if the interval is reached.
|
||||
func (t *IntervalTimer) UpdateReset(dt float32) bool {
|
||||
if res := t.Update(dt); res {
|
||||
t.Reset()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Ticked returns true if the current accumulated time has reached or
|
||||
// exceeded the configured interval. Does not modify the timer.
|
||||
func (t IntervalTimer) Ticked() bool {
|
||||
return t.time >= t.interval
|
||||
}
|
||||
|
||||
// Reset sets the internal time counter back to zero.
|
||||
func (t *IntervalTimer) Reset() {
|
||||
t.time = 0
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue