1+ #include " AnimatorComponent.hpp"
2+ #include " Renderer/Renderer.hpp"
3+ #include " Renderer/Sprite.hpp"
4+ #include " Scene/Scene.hpp"
5+
6+ AnimatorComponent::AnimatorComponent (const char * atlasResourceName)
7+ : _atlas(GetResource<SpriteAtlasResource>(atlasResourceName))
8+ {
9+
10+ }
11+
12+
13+ const AtlasAnimation* SpriteAtlas::GetAnimation (StringId name) const
14+ {
15+ for (const auto & animation : _animations)
16+ {
17+ if (animation.name == name)
18+ {
19+ return &animation;
20+ }
21+ }
22+
23+ FatalError (" No such animation: %s" , name.ToString ());
24+ }
25+
26+ void AnimatorComponent::PlayAnimation (StringId name, AnimationPlayMode mode)
27+ {
28+ if (_atlas == nullptr ) return ;
29+
30+ _currentAnimation = _atlas->Get ().GetAnimation (name);
31+
32+ _frameDuration = 1 .0f / static_cast <float >(_currentAnimation->fps );
33+ _relativeTime = 0 ;
34+ _currentAnimationIndex = 0 ;
35+ _mode = mode;
36+ _animationComplete = false ;
37+ }
38+
39+ void AnimatorComponent::Render (Renderer* renderer)
40+ {
41+ if (_currentAnimation == nullptr )
42+ {
43+ return ;
44+ }
45+
46+ Sprite currentFrame;
47+ _atlas->Get ().GetFrame (_currentAnimation->frames [_currentAnimationIndex], ¤tFrame);
48+
49+ renderer->RenderSprite (
50+ ¤tFrame,
51+ owner->ScreenCenter () + offsetFromCenter,
52+ depth,
53+ Vector2 (1 , 1 ),
54+ 0 ,
55+ _flipHorizontal,
56+ blendColor);
57+ }
58+
59+ void AnimatorComponent::SetSpriteAtlas (SpriteAtlasResource* atlas)
60+ {
61+ _atlas = atlas;
62+ }
63+
64+ void AnimatorComponent::Pause ()
65+ {
66+ _originalMode = _mode;
67+ _mode = AnimationPlayMode::Paused;
68+ }
69+
70+ void AnimatorComponent::Resume ()
71+ {
72+ if (_mode == AnimationPlayMode::Paused)
73+ {
74+ _mode = _originalMode;
75+ }
76+ }
77+
78+ void AnimatorComponent::GetCurrentFrame (Sprite& outFrame) const
79+ {
80+ _atlas->Get ().GetFrame (_currentAnimation->frames [_currentAnimationIndex], &outFrame);
81+ }
82+
83+ void AnimatorComponent::NextFrame ()
84+ {
85+ if (_animationComplete)
86+ {
87+ return ;
88+ }
89+
90+ ++_currentAnimationIndex;
91+
92+ if (_currentAnimationIndex >= _currentAnimation->frames .size ())
93+ {
94+ if (_mode == AnimationPlayMode::Loop)
95+ {
96+ _currentAnimationIndex = _currentAnimationIndex % _currentAnimation->frames .size ();
97+ }
98+ else
99+ {
100+ _currentAnimationIndex = _currentAnimation->frames .size () - 1 ;
101+ _animationComplete = true ;
102+ return ;
103+ }
104+ }
105+ }
106+
107+ void AnimatorComponent::Update (float deltaTime)
108+ {
109+ if (_mode != AnimationPlayMode::Paused)
110+ {
111+ // Update current frame
112+ _relativeTime += GetScene ()->relativeTime - _absoluteTime;
113+
114+ while (_relativeTime >= _frameDuration)
115+ {
116+ _relativeTime -= _frameDuration;
117+ NextFrame ();
118+ }
119+ }
120+
121+ _absoluteTime = GetScene ()->relativeTime ;
122+ }
0 commit comments