-
Notifications
You must be signed in to change notification settings - Fork 0
/
animation.go
58 lines (50 loc) · 1.5 KB
/
animation.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
package main
import (
"github.com/faiface/pixel"
)
// Animation on a horizontal spreadsheet
type animation struct {
partialSprite *pixel.Sprite
frameSize pixel.Vec
currentFrame int
totalFrames int
secondsPerFrame float64
currentSeconds float64
looping bool
isFinished bool
}
func newAnimation(partialSprite *pixel.Sprite, frameSize pixel.Vec, secondsPerFrame float64, looping bool) *animation {
totalFrames := int(partialSprite.Picture().Bounds().W()) / int(frameSize.Y)
return &animation{
partialSprite: partialSprite,
frameSize: frameSize,
currentFrame: 0,
totalFrames: totalFrames,
secondsPerFrame: secondsPerFrame,
looping: looping,
}
}
func (a *animation) advance(dt float64) {
if a.isFinished {
return
}
a.currentSeconds += dt
if a.currentSeconds < a.secondsPerFrame {
return
}
framesToAdvance := int(a.currentSeconds / a.secondsPerFrame)
a.currentSeconds -= a.secondsPerFrame * float64(framesToAdvance)
for i := 0; i < framesToAdvance && !a.isFinished; i++ {
movedRight := a.partialSprite.Frame().Moved(pixel.V(a.frameSize.X, 0))
// if movedRight is completely inside the spritesheet
if a.partialSprite.Picture().Bounds().Intersect(movedRight) == movedRight {
a.partialSprite.Set(a.partialSprite.Picture(), movedRight)
a.currentFrame++
} else if a.looping {
firstFrame := pixel.R(0, 0, a.frameSize.X, a.frameSize.Y)
a.partialSprite.Set(a.partialSprite.Picture(), firstFrame)
} else {
a.isFinished = true
}
}
}