【发布时间】:2014-07-17 02:05:35
【问题描述】:
我想为我的迷你游戏制作插值。有 2 个 SDL_Textures,当我先单击然后再单击时,它们的位置会交换,但没有移动动画。 那么如何为 SDL_Textures 制作动画位置交换呢?
void MainLoop() {
SDL_Event Event;
float t = 0.0f;
float dt = 0.1f;
float currentTime = 0.0f;
float accumulator = 0.0f;
while (Running)
{
while(SDL_PollEvent(&Event)) {
OnEvent(&Event);
}
const float newTime = SDL_GetTicks();
float frameTime = newTime - currentTime;
const Uint32 maxFrameTime = 1000; // 1 sec per frame is the slowest we allow
if( frameTime > maxFrameTime) {
frameTime = maxFrameTime;
}
currentTime = newTime;
accumulator += frameTime;
while( accumulator >= dt )
{
this->UpdatePositions(); // simulate a "frame" of logic at a different FPS than we simulate a frame of rendering
accumulator -= dt;
t += dt;
}
Render();
}
主要渲染方法:
void Puzzle::Render() const {
SDL_RenderClear(renderer);
for (int i = 0; i < blocksNum; ++i)
{
Rectangle texRect = normalizeTexCoords(blockRect(blocks[i]));
Rectangle scrRectOrigin = blockRect(i);
DrawRect(scrRectOrigin, i, texRect);
}
SDL_RenderPresent(renderer);
}
void DrawRect(const Rectangle& screenCoords, int textureId, const Rectangle& textureCoord) {
SDL_Texture *texture = blockTexture(blocks[textureId]);
renderTexture(texture, renderer, (int)screenCoords.left, (int)screenCoords.top, (int)blockWidth, (int)blockHeight);
//SDL_DestroyTexture(texture2);
}
void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int w, int h) {
// Destination rectangle position
SDL_Rect dst;
dst.x = x; dst.y = y; dst.w = w; dst.h = h;
SDL_RenderCopy(ren, tex, NULL, &dst);
}
在我的 UpdatePosition 方法中,我想让我的 SDL_Textures 移动,但它仍然在没有动画的情况下进行交换。
void Puzzle::UpdatePositions()
{
if (secondSwappedBlock != -1) {
Rectangle firstRect = blockRect(blocks[firstSwappedBlock]);
firstRect.left += speed * deltaTime;
firstRect.right += speed * deltaTime;
SDL_Texture *texture = blockTexture(blocks[firstSwappedBlock]);
renderTexture(texture, renderer, (int)firstRect.left, (int)firstRect.top, (int)blockWidth, (int)blockHeight);
}
}
void Puzzle::SwapBlocks(const int first, const int second) const
{
if (first != second)
{
const int t = blocks[first];
blocks[first] = blocks[second];
blocks[second] = t;
}
}
【问题讨论】:
-
代码中的注释表明 update 和 render 是完全分离的东西(应该如此),但您的 update 函数调用
renderTexture而不是更新blockRects。这是为什么?speed是什么?deltaTime是什么?你如何触发交换?为什么你的更新只重绘第一个块而不是第二个块,甚至没有计算它应该动画的方向(硬编码为“向右移动”,甚至没有指定多长时间)? -
我正在尝试向某个方向移动图像,但它没有移动。我正在尝试更新 blockRect、speed 和 deltaTime,它是常量。添加交换块
-
你在没有任何动画的情况下改变了 SwapBlocks 中的坐标。当然,它会立即交换。动画开始应该只是提高一些标志并保存块的原始位置;然后,在每一帧上,计算新的位置,直到动画没有完全播放。然后放下动画标志并固定最终位置。
-
我想,在 SwapBlock 中我会立即更改坐标,在更新循环中我会精确地进行插值。而且以这种方式,我不明白为什么我需要“更新”方法,如果我都可以在 render 中做的话。你能用伪代码写 unswer 我会投票吗