-
Notifications
You must be signed in to change notification settings - Fork 0
/
animator.go
118 lines (93 loc) · 2.1 KB
/
animator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"fmt"
"io/ioutil"
"path"
"time"
"github.com/veandco/go-sdl2/sdl"
)
type animator struct {
container *element
sequences map[string]*sequence
current string
lastFrameChange time.Time
finished bool
}
func newAnimator(
container *element,
sequences map[string]*sequence,
defaultSequence string) *animator {
var an animator
an.container = container
an.sequences = sequences
an.current = defaultSequence
an.lastFrameChange = time.Now()
return &an
}
func (an *animator) onUpdate() error {
sequence := an.sequences[an.current]
frameInterval := float64(time.Second) / sequence.sampleRate
if time.Since(an.lastFrameChange) >= time.Duration(frameInterval) {
an.finished = sequence.nextFrame()
an.lastFrameChange = time.Now()
}
return nil
}
func (an *animator) onDraw(renderer *sdl.Renderer) error {
tex := an.sequences[an.current].texture()
return drawTexture(
tex,
an.container.position,
an.container.rotation,
renderer)
}
func (an *animator) onCollision(other *element) error {
return nil
}
func (an *animator) setSequence(name string) {
an.current = name
an.lastFrameChange = time.Now()
}
type sequence struct {
textures []*sdl.Texture
frame int
sampleRate float64
loop bool
}
func newSequence(
filepath string,
sampleRate float64,
loop bool,
renderer *sdl.Renderer) (*sequence, error) {
var seq sequence
files, err := ioutil.ReadDir(filepath)
if err != nil {
return nil, fmt.Errorf("reading directory %v: %v", filepath, err)
}
for _, file := range files {
filename := path.Join(filepath, file.Name())
tex, err := loadTextureFromBMP(filename, renderer)
if err != nil {
return nil, fmt.Errorf("loading sequence frame: %v", err)
}
seq.textures = append(seq.textures, tex)
}
seq.sampleRate = sampleRate
seq.loop = loop
return &seq, nil
}
func (seq *sequence) texture() *sdl.Texture {
return seq.textures[seq.frame]
}
func (seq *sequence) nextFrame() bool {
if seq.frame == len(seq.textures)-1 {
if seq.loop {
seq.frame = 0
} else {
return true
}
} else {
seq.frame++
}
return false
}