-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpriteComponent.h
97 lines (74 loc) · 1.82 KB
/
SpriteComponent.h
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
#pragma once
#include "Components.h"
#include "SDL.h"
#include "TextureManager.h"
#include "Animation.h"
#include <map>
#include "AssetManager.h"
class SpriteComponent : public Component
{
private:
TransformComponent* transform;
SDL_Texture* texture;
SDL_Rect srcRect, destRect;
bool animated = false;
int frames = 0;
int speed = 100;
public:
int animIndex = 0;
std::map<const char*, Animation> animations;
SpriteComponent() = default;
SpriteComponent(std::string id)
{
setTex(id);
}
SpriteComponent(std::string id, bool isAnimated)
{
animated = isAnimated;
Animation front = Animation(0, 2, 250);
Animation back = Animation(1, 2, 250);
Animation right = Animation(2, 2, 250);
Animation left = Animation(3, 2, 250);
animations.emplace("Front", front);
animations.emplace("Back", back);
animations.emplace("Right", right);
animations.emplace("Left", left);
Play("Back");
setTex(id);
}
~SpriteComponent()
{}
void setTex(std::string id)
{
texture = Game::assets->GetTexture(id);
}
void init() override
{
transform = &entity->getComponent<TransformComponent>();
srcRect.x = srcRect.y = 0;
srcRect.w = transform->width;
srcRect.h = transform->height;
}
void update() override
{
if (animated)
{
srcRect.x = srcRect.w * static_cast<int>((SDL_GetTicks() / speed) % frames);
}
srcRect.y = animIndex * transform->height;
destRect.x = static_cast<int>(transform->position.x);
destRect.y = static_cast<int>(transform->position.y);
destRect.h = transform->height * transform->scale;
destRect.w = transform->width * transform->scale;
}
void draw() override
{
TextureManager::Draw(texture, srcRect, destRect);
}
void Play(const char* animName)
{
frames = animations[animName].frames;
animIndex = animations[animName].index;
speed = animations[animName].speed;
}
};