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-09-01 09:48:01 +10:00
|
|
|
// A nil *Anim can be used, but always returns 0 for the current frame.
|
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 {
|
2021-09-01 09:48:01 +10:00
|
|
|
if a == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2021-08-23 20:28:49 +10:00
|
|
|
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.
|
2021-09-01 09:48:01 +10:00
|
|
|
func (a *Anim) CurrentFrame() int {
|
|
|
|
if a == nil {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
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-09-01 09:48:01 +10:00
|
|
|
func (a *Anim) Reset() {
|
|
|
|
if a == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
a.Index, a.Ticks = 0, 0
|
|
|
|
}
|
2021-08-05 15:24:16 +10:00
|
|
|
|
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-09-01 09:48:01 +10:00
|
|
|
if a == nil {
|
|
|
|
return nil
|
|
|
|
}
|
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
|
|
|
|
}
|