~~stoggle_buttons~~ {{:raylib:flappybird아이템에이전트만들기.png?600|아이템 애니메이션}} ===== 스타팅 파일 ===== * [[raylib:flappybird:메인메뉴를_키보드로_조작하기|키보드로 메인메뉴 조작하기]]에서 이어져 오는 강좌다 * {{ :raylib:flappybird_6.zip |키보드로 메인메뉴 조작하기}} 프로젝트 파일을 다운받아서 시작하자 ===== 스프라이트시트로 게임 에니메이션 구현하기 개념 ===== 2D 애니메이션에 있어서 가장 전통적이고 간단한 방법은 그림을 여러장 만든 후에 빠르게 돌리는 것이다. 이는 영사기에서 필름을 빠르게 돌리는 것과 동일한 원리이다. 최초에 한번 큰 이미지 파일을 불러 온 후에, 각 이미지 파일의 부분만 출력해주면 되는 것이기 때문에 부하도 적고 연산도 빠르다. {{:raylib:coinspritesheets.png?600|코인 스프라이트 시트}} 위 그림은 47X47개의 코인 그림이 가로로 31개가 나열되어 있는 그림이다. 31번 빠르게 돌려주면 애니메이션이 완성되는 것이다. 따라서 매프레임마다 X위치만 바꿔주면 애니메이션을 만들 수 있다. ===== 애니메이션 구현해 보기 ===== ==== 1. coin.h ==== 파일 전체의 코드를 살펴보자 #pragma once #include "raylib.h" class Coin { public: void Init(); void Update(); void Draw(); ~Coin(); private: Vector2 pos; // 텍스처 로드하기 // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) Texture2D CoinSprite; // Texture loading; Rectangle frameRec; int currentFrame = 0; int framesCounter = 0; int framesSpeed = 8; // Number of spritesheet frames shown by second }; 기본적인 함수는 전과 별로 다를바가 없다. 불러올 그림은 Texture2D로 선언하였으며, 한 프레임에 보여줄 구간은 Rectangle로 네모의 값을 선언하였다. 현재 프레임과, 프레임을 조작할 변수들을 int로 선언하였다. ==== 2. coin.cpp ==== 역시 전체 파일을 보여주는 것이 더 직관적으로 쉽게 이해될 것이다. #include "coin.h" #define SPRITE_NUMBERS 31 void Coin::Init() { pos = {800, 400}; CoinSprite = LoadTexture("Assets/coinspritesheets.png"); // Texture loading frameRec = { 0.0f, 0.0f, (float)CoinSprite.width/SPRITE_NUMBERS, (float)CoinSprite.height }; currentFrame = 0; framesCounter = 0; framesSpeed = 16; // Number of spritesheet frames shown by second } void Coin::Update() { framesCounter++; if (framesCounter >= (60/framesSpeed)) // FPS를 60으로 설정했으므로 60을 프레임스피드로 나눈다. 그러면 1초당 몇번 돌릴지 결과 값이 나온다. { framesCounter = 0; currentFrame++; if (currentFrame > SPRITE_NUMBERS) currentFrame = 0; frameRec.x = (float)currentFrame*(float)CoinSprite.width/SPRITE_NUMBERS; } } void Coin::Draw() { DrawTextureRec(CoinSprite, frameRec, pos, WHITE); // Draw part of the texture } Coin::~Coin() { UnloadTexture(CoinSprite); // Texture unloading } 한 프레임당 보여줄 영역을 frameRec으로 설정하였다. 우리는 FPS를 60으로 설정하였으므로 1초당 60번 업데이트 메서드가 이루어진다. 이에 착안하면 1초당 애니메이션 프레임을 어떻게 설정할 수 있는지가 나온다. 1초당 몇장을 보여줄지는 60을 framesSpeed로 나눈 값이다. 만약 framespeed가 1이면 1초당 1장의 정지그림이 나온다. 이 값이 커지면 점점 빨라질 것이다. 우리는 framespeed를 16으로 설정하였다. 그리고 FPS 정의상 frameCounter는 60분의 1초 간격으로 1씩 증가한다. 따라서 단순히 frameCounter만으로 프레임을 증가시키면 애니메이션이 너무 빨라지므로 frameCounter를 늘리기 위하여 framesCounter >= (60/framesSpeed) 로 1초당 보여줄 애니메이션 그림의 양을 설정한 것이다. 이후 currentFrame이 1씩 증가하면 frameRec의 x값을 그림 1장의 너비 만큼씩 증가함으로써 그림을 연속적으로 보여주는 것이다. 나머지는 따로 설명할 필요가 없을 것이다. 다음에는 [[raylib:flappybird:포인터를_이용하여_최적화하기|포인터를 이용하여 최적화하기]]를 해보겠다