ichigo/engine/anim.go

54 lines
1.1 KiB
Go
Raw Normal View History

2021-07-31 17:15:32 +10:00
package engine
2021-08-25 15:04:38 +10:00
import "encoding/gob"
2021-08-23 20:28:49 +10:00
// Ensure Anim satisfies Animer.
var _ Animer = &Anim{}
2021-08-25 15:04:38 +10:00
func init() {
gob.Register(&Anim{})
}
2021-08-23 20:28:49 +10:00
// AnimFrame describes a frame in an animation.
type AnimFrame struct {
Frame int // show this frame
Duration int // for this long, in ticks
}
// Anim is n animation being displayed, together with the current state.
2021-07-31 17:15:32 +10:00
type Anim struct {
2021-08-23 20:28:49 +10:00
Frames []AnimFrame
OneShot bool
Index int
Ticks int
}
// Copy makes a shallow copy of the anim.
func (a *Anim) Copy() *Anim {
a2 := *a
return &a2
2021-07-31 17:15:32 +10:00
}
2021-08-23 20:28:49 +10:00
// CurrentFrame returns the frame number for the current index.
func (a *Anim) CurrentFrame() int { return a.Frames[a.Index].Frame }
2021-07-31 17:15:32 +10:00
2021-08-23 20:28:49 +10:00
// Reset resets both Index and Ticks to 0.
2021-08-05 15:24:16 +10:00
func (a *Anim) Reset() { a.Index, a.Ticks = 0, 0 }
2021-07-31 17:15:32 +10:00
// Update increments the tick count and advances the frame if necessary.
func (a *Anim) Update() error {
2021-07-31 17:17:26 +10:00
a.Ticks++
2021-08-23 20:28:49 +10:00
if a.OneShot && a.Index == len(a.Frames)-1 {
2021-07-31 17:15:32 +10:00
// on the last frame of a one shot so remain on final frame
return nil
}
2021-08-23 20:28:49 +10:00
if a.Ticks >= a.Frames[a.Index].Duration {
2021-07-31 17:17:26 +10:00
a.Ticks = 0
a.Index++
2021-07-31 17:15:32 +10:00
}
2021-08-23 20:28:49 +10:00
if !a.OneShot && a.Index >= len(a.Frames) {
2021-07-31 17:17:26 +10:00
a.Index = 0
2021-07-31 17:15:32 +10:00
}
return nil
}