2024-02-12 17:27:52 +01:00
|
|
|
package components
|
|
|
|
|
|
|
|
|
|
import (
|
2024-02-13 18:15:52 +01:00
|
|
|
"math/rand"
|
2024-02-12 17:27:52 +01:00
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/hajimehoshi/ebiten/v2"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type Timer struct {
|
2024-02-13 18:15:52 +01:00
|
|
|
CurrentTicks int
|
|
|
|
|
TargetTicks int
|
|
|
|
|
Running bool
|
|
|
|
|
Id int
|
2024-02-12 17:27:52 +01:00
|
|
|
}
|
|
|
|
|
|
2024-02-13 18:15:52 +01:00
|
|
|
func NewTimer() *Timer {
|
2024-02-12 17:27:52 +01:00
|
|
|
return &Timer{}
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-13 18:15:52 +01:00
|
|
|
func (timer *Timer) Start(duration time.Duration) {
|
2024-04-01 19:43:37 +02:00
|
|
|
timer.Reset()
|
|
|
|
|
|
2024-02-12 17:27:52 +01:00
|
|
|
min := int(1000 / ebiten.TPS()) // 16.66ms == 1 tick
|
|
|
|
|
|
2024-02-13 18:15:52 +01:00
|
|
|
dur := duration
|
|
|
|
|
if int(duration.Milliseconds()) < min {
|
|
|
|
|
dur = time.Duration(1000/ebiten.TPS()) * time.Millisecond
|
2024-02-12 17:27:52 +01:00
|
|
|
}
|
|
|
|
|
|
2024-02-13 18:15:52 +01:00
|
|
|
timer.TargetTicks = int(dur.Milliseconds()) / min // id d=50, then 50 / 16.6 =
|
|
|
|
|
timer.Running = true
|
|
|
|
|
timer.Id = rand.Int()
|
2024-02-12 17:27:52 +01:00
|
|
|
}
|
|
|
|
|
|
2024-02-13 18:15:52 +01:00
|
|
|
func (timer *Timer) Update() {
|
|
|
|
|
if (timer.CurrentTicks < timer.TargetTicks) && timer.Running {
|
|
|
|
|
timer.CurrentTicks++
|
2024-02-12 17:27:52 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-13 18:15:52 +01:00
|
|
|
func (timer *Timer) IsReady() bool {
|
|
|
|
|
return (timer.CurrentTicks >= timer.TargetTicks) && timer.Running
|
2024-02-12 17:27:52 +01:00
|
|
|
}
|
|
|
|
|
|
2024-02-13 18:15:52 +01:00
|
|
|
func (timer *Timer) Reset() {
|
|
|
|
|
timer.CurrentTicks = 0
|
|
|
|
|
timer.TargetTicks = 0
|
|
|
|
|
timer.Running = false
|
2024-02-12 17:27:52 +01:00
|
|
|
}
|