package tins2021 import ( "math/rand" "time" "opslag.de/schobers/geom" ) type Animation struct { LastUpdate time.Time Frame int } type Animations struct { Values map[geom.Point]*Animation Interval time.Duration Frames int AutoReset bool RandomInit bool } func NewAnimations(interval time.Duration, frames int, autoReset, randomInit bool) *Animations { return &Animations{ Values: map[geom.Point]*Animation{}, Interval: interval, Frames: frames, AutoReset: autoReset, RandomInit: randomInit, } } func (a *Animations) Update() { now := time.Now() update := now.Add(-a.Interval) for _, value := range a.Values { if value.Frame == a.Frames { break } for value.LastUpdate.Before(update) { value.LastUpdate = value.LastUpdate.Add(a.Interval) value.Frame = value.Frame + 1 if value.Frame == a.Frames { if a.AutoReset { value.Frame = 0 } else { break } } } } } func (a *Animations) newAnimation() *Animation { if a.RandomInit { return &Animation{ LastUpdate: time.Now().Add(time.Duration(-rand.Int63n(int64(a.Interval)))), Frame: rand.Intn(a.Frames), } } return &Animation{ LastUpdate: time.Now(), Frame: 0, } } func (a *Animations) Frame(pos geom.Point) int { value, ok := a.Values[pos] if !ok { value = a.newAnimation() a.Values[pos] = value } return value.Frame }