Game Programming in C++
Game Programming in C++ Chapter2 - AnimationComponent
skyho
2025. 9. 6. 21:58
반응형

책의 소스 코드를 직접 작성해보면서 정리한 글입니다. (실습환경: windows)
책 소스 코드: GitHub - gameprogcpp/code: Game Programming in C++ Code
1. Animation Component 역할(기능)
Sprite Component를 상속받아서 구현한다.
| 기능 | 설명 |
| Animtaion 기능 | Sprite Component에 Animation 기능을 더한다 |
2. Animation Component 생성 동작
Sprite를 상속받았기 때문에, 기본적으로 동작이 유사하다.
- Step 1
부모인 Sprite 생성자를 통해서 Game Manager에 등록된다.
SpriteComponent::SpriteComponent(Actor* owner, int draw_order) : Component(owner), _draw_order(draw_order), _texture(nullptr),
_texture_width(0), _texture_height(0)
{
_owner->getGameManager()->addSprite(this);
}
- Step 2
Sprite 부모의 Component를 통해서 Actor에게 등록된다.
Component::Component(Actor* owner) : _owner(owner)
{
_owner->addComponent(this);
}
3. AnimationComponent.hpp
#pragma once
#include <vector>
#include "SpriteComponent.hpp"
class AnimationComponent : public SpriteComponent
{
public:
AnimationComponent(class Actor* owner, int draw_order = 100);
~AnimationComponent();
void setAnimationTextures(std::vector<SDL_Texture*> ani_texture);
void setFPS(float fps);
virtual void update(float delta_time) override;
private:
std::vector<SDL_Texture*> _animation_textures;
float _animation_fps; // animation frame rate
float _current_frame; // current frame displayed
};
4. AnimationComponent.cpp
frame에 맞는 텍스처 한장을 출력하면 되기 때문에, Sprite의 draw()를 이용해 출력한다. (not override)
frame에 맞는 텍스처 한장을 선택하기 위해서, update()를 override 했다. (Component와 Sprite에는 update 미구현)
#include "Actor.hpp"
#include "AnimationComponent.hpp"
AnimationComponent::AnimationComponent(Actor* owner, int draw_order) : SpriteComponent(owner, draw_order), _animation_fps(24.0f),
_current_frame(0)
{
}
AnimationComponent::~AnimationComponent()
{
}
void AnimationComponent::update(float delta_time)
{
// Update the current frame based on frame rate
// and delta time
_current_frame += _animation_fps * delta_time;
// Wrap current frame if needed
while (_current_frame >= _animation_textures.size())
{
_current_frame -= _animation_textures.size();
}
// Set the current texture
int idx = static_cast<int>(_current_frame);
_texture = _animation_textures[idx];
setTexture(_texture);
}
void AnimationComponent::setAnimationTextures(std::vector<SDL_Texture*> ani_texture)
{
_animation_textures = ani_texture;
}
void AnimationComponent::setFPS(float fps)
{
_animation_fps = fps;
}반응형