我刚刚从 youtube 复制了一个非常简单的动画代码来学习如何在 raylib 中制作动画。但整个代码都是写在main函数里面的。我希望将其组织起来并分开。这是代码:
#include "include/raylib.h"
int main()
{
const int screenWidth = 1200;
const int screenHeight = 800;
InitWindow(screenWidth, screenHeight, "2D Platformer");
SetTargetFPS(60);
Texture2D run_sprite = LoadTexture("sprites/Fighter/Run.png");
Rectangle source = {0.f, 0.f, (float)run_sprite.width / 8.0f, (float)run_sprite.height};
Vector2 position = {0, screenHeight / 2};
int frame = 0;
float runningTime{};
const float updateTime{1.f/12.f};
while (WindowShouldClose() == false)
{
//UPDATE VARIABLES
float deltaTime = GetFrameTime();
runningTime += deltaTime;
if (runningTime >= updateTime)
{
runningTime = 0.f;
source.x = (float)frame * source.width;
frame++;
if (frame > 8)
{
frame = 0;
}
}
//START DRAWING
BeginDrawing();
ClearBackground(RAYWHITE);
DrawTextureRec(run_sprite, source, position, WHITE);
EndDrawing();
}
CloseWindow();
}
我尝试将其分为以下功能:
Texture2D run_sprite;
void load_textures()
{
run_sprite = LoadTexture("sprites/Fighter/Run.png");
}
int frame = 0;
float runningTime{};
const float updateTime{1.f/12.f};
Rectangle source = {0.f, 0.f, (float)run_sprite.width / 8.0f, (float)run_sprite.height};
void update_run_animation()
{
runningTime += deltaTime;
if (runningTime >= updateTime)
{
runningTime = 0.f;
source.x = (float)frame * source.width;
frame++;
if (frame > 8)
{
frame = 0;
}
}
}
Vector2 position = {0, screenHeight / 2};
void render_run_animation()
{
DrawTextureRec(run_sprite, source, position, WHITE);
}
这是 main 函数内代码的实现版本:
int main()
{
const int screenWidth = 1200;
const int screenHeight = 800;
InitWindow(screenWidth, screenHeight, "2D Platformer");
SetTargetFPS(60);
load_textures();
while (WindowShouldClose() == false)
{
update_run_animation();
BeginDrawing();
ClearBackground(RAYWHITE);
render_run_animation();
EndDrawing();
}
CloseWindow();
}
但是当我运行这个时,它只是创建一个窗口而不是绘制纹理。我尝试从每个函数变量中获取输出来调试它。结论是,当涉及到“update_run_animation”函数时,“source.width”变量给出的默认值是0。我不知道到底是什么问题,所以我发布了整个代码。抱歉表达太长了。
全局变量的初始化发生在main
函数运行之前。因此,您在初始化
source
(和 position
)时使用的值将不是您所期望的。在使用变量之前,您需要在 main
函数中显式初始化(分配)这些变量。