R-Type 0.1
Loading...
Searching...
No Matches
AnimationSystem.hpp
1#pragma once
2
3#include "Logger/Logger.hpp"
4#include "components/Animation.hpp"
5#include "systems/RenderConcept.hpp"
6#include <ISystem.hpp>
7
8namespace rtk::systems {
17class AnimationSystem final : public rtk::ecs::ISystem {
18public:
19 AnimationSystem() = default;
20 ~AnimationSystem() override = default;
21
25 void onStart(rtk::ecs::Registry &) override {
26 LOG_INFO("Load Animation System");
27 }
28
34 void update(rtk::ecs::Registry &reg, float dt) override {
35 auto view = reg.view<component::Animation, ecs::concepts::SpriteData>();
36
37 auto &animations = reg.get_components<component::Animation>();
38 auto &sprites = reg.get_components<ecs::concepts::SpriteData>();
39
40 for (auto entity : view) {
41 auto *anim = animations.get(entity);
42 auto *sprite = sprites.get(entity);
43
44 if (!anim || !sprite) {
45 continue;
46 }
47
48 if (anim->playing && anim->totalFrames > 1 &&
49 anim->frameDuration > 0.0f) {
50 anim->elapsedTime += dt;
51
52 while (anim->elapsedTime >= anim->frameDuration) {
53 anim->elapsedTime -= anim->frameDuration;
54 anim->currentFrame++;
55
56 if (anim->currentFrame >= anim->totalFrames) {
57 if (anim->loop) {
58 anim->currentFrame = 0;
59 } else {
60 anim->currentFrame = anim->totalFrames - 1;
61 anim->playing = false;
62 break;
63 }
64 }
65 }
66 }
67
68 uint16_t frameIdx = anim->currentFrame;
69 if (anim->reverse && anim->totalFrames > 1) {
70 frameIdx = (anim->currentFrame < anim->totalFrames)
71 ? (anim->totalFrames - 1 - anim->currentFrame)
72 : 0;
73 }
74
75 uint16_t currentColumn =
76 (anim->columns > 0) ? (frameIdx % anim->columns) : frameIdx;
77 uint16_t currentRow =
78 (anim->columns > 0) ? (frameIdx / anim->columns) : 0;
79
80 sprite->textureRect.x =
81 anim->startX + (currentColumn * (anim->frameWidth + anim->paddingX));
82 sprite->textureRect.y =
83 anim->startY + (currentRow * (anim->frameHeight + anim->paddingY));
84 if (anim->frameWidth > 0) {
85 sprite->textureRect.width = anim->frameWidth;
86 }
87 if (anim->frameHeight > 0) {
88 sprite->textureRect.height = anim->frameHeight;
89 }
90 }
91 }
92
96 void onStop(rtk::ecs::Registry &) override {}
97};
98
100} // namespace rtk::systems
Advances sprite sheet animations and updates texture rectangles.
Definition AnimationSystem.hpp:17
void onStop(rtk::ecs::Registry &) override
Does nothing.
Definition AnimationSystem.hpp:96
void update(rtk::ecs::Registry &reg, float dt) override
Moves each animation forward by the elapsed time.
Definition AnimationSystem.hpp:34
void onStart(rtk::ecs::Registry &) override
Logs that the system is loaded.
Definition AnimationSystem.hpp:25
Sprite sheet animation played by changing the texture rectangle.
Definition Animation.hpp:17
uint16_t currentFrame
Index of the visible frame.
Definition Animation.hpp:21
Everything the renderer needs to draw one sprite.
Definition RenderConcept.hpp:338