/
animated.rb
86 lines (69 loc) · 1.75 KB
/
animated.rb
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
# keeps track of an image for you based on the actor's class, and
# current action, and frame num
# by default it expects images to be:
# data/graphics/classname/action/01..n.png
class Animated < Behavior
# TODO uh oh.. inheritance again!! maybe remove the base class all together?
construct_with :actor, :resource_manager
attr_accessor :frame_time, :frame_num, :animating, :frame_update_time
def setup
@images = {}
@frame_update_time = @opts[:frame_update_time]
@frame_update_time ||= 60
@frame_time = 0
# all animated actors have to have an idle animation
# data/graphics/ship/idle/1.png
@frame_num = 0
self.action = :idle
relegates :image, :width, :height,
:start_animating, :stop_animating, :animated,
:action, :action=
end
def animated
self
end
def width
image.width
end
def height
image.height
end
def update(time)
return unless @animating
@frame_time += time
if @frame_time > @frame_update_time
next_frame
@frame_time = @frame_time-@frame_update_time
end
end
def next_frame()
@frame_num = (@frame_num + 1) % @images[@action].size
end
# load all the images for this action
def load_action(action)
@actor.resource_manager.load_animation_set @actor, action
end
def action
@action
end
def action=(new_action)
@images[new_action] ||= load_action(new_action)
if @images[new_action].size > 1
start_animating
else
stop_animating
end
@frame_num = 0
@action = new_action
end
# returns the current image, or nil if no action is defined
def image
@images[@action][@frame_num]
end
def start_animating
@animating = true
end
def stop_animating
@animating = false
end
end