-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnimatedSprite.cpp
More file actions
88 lines (73 loc) · 2.39 KB
/
Copy pathAnimatedSprite.cpp
File metadata and controls
88 lines (73 loc) · 2.39 KB
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
#include "AnimatedSprite.h"
#include "Graphics.h"
AnimatedSprite::AnimatedSprite() {}
AnimatedSprite::AnimatedSprite(Graphics& graphics, const std::string& filePath, int sourceX, int sourceY, int width, int height,
float posX, float posY, float timeToUpdate) :
Sprite(graphics, filePath, sourceX, sourceY, width, height, posX, posY),
_frameIndex(0),
_timeToUpdate(timeToUpdate),
_visible(true),
_currentAnimationOnce(false),
_currentAnimation(""),
_timeElapsed(0)
{}
void AnimatedSprite::addAnimation(int frames, int x, int y, std::string name, int width, int height, Vector2 offset) {
std::vector<SDL_Rect> rectangles;
for (int i = 0; i < frames; i++) {
SDL_Rect newRect = { (i + x) * width, y, width, height };
rectangles.push_back(newRect);
}
_animations.insert(std::pair<std::string, std::vector<SDL_Rect>>(name, rectangles));
_offsets.insert(std::pair<std::string, Vector2> (name, offset));
}
void AnimatedSprite::resetAnimations() {
_animations.clear();
_offsets.clear();
}
void AnimatedSprite::playAnimation(std::string animation, bool once) {
_currentAnimation = once;
if (_currentAnimation != animation) {
_currentAnimation = animation;
_frameIndex = 0;
}
}
void AnimatedSprite::setVisible(bool visible) {
_visible = visible;
}
void AnimatedSprite::stopAnimation() {
_frameIndex = 0;
animationDone(_currentAnimation);
}
void AnimatedSprite::update(float elapsedTime) {
Sprite::update();
_timeElapsed += elapsedTime;
if (_timeElapsed > _timeToUpdate) {
_timeElapsed -= _timeToUpdate;
if (_frameIndex < _animations[_currentAnimation].size() - 1) {
_frameIndex++;
}
else {
if (_currentAnimationOnce == true) {
setVisible(false);
}
_frameIndex = 0;
animationDone(_currentAnimation);
}
}
}
void AnimatedSprite::draw(Graphics& graphics, int x, int y) {
if (_visible) {
SDL_Rect destinationRectangle;
destinationRectangle.x = x + _offsets[_currentAnimation].x;
destinationRectangle.y = y + _offsets[_currentAnimation].y;
destinationRectangle.w = _sourceRect.w * globals::SPRITE_SC;
destinationRectangle.h = _sourceRect.h * globals::SPRITE_SC;
SDL_Rect sourceRect = _animations[_currentAnimation][_frameIndex];
graphics.blitSurface(_spriteSheet, &sourceRect, &destinationRectangle);
}
}
void AnimatedSprite::animationDone(std::string currentAnimation) {
}
void AnimatedSprite::setupAnimations() {
addAnimation(3, 0, 0, "RunLeft", 16, 16, Vector2(0, 0));
}