每次按键从零开始计数

Start count from zero on each keypress

本文关键字:从零开始      更新时间:2023-10-16

我有一个程序,我在屏幕上绘制图像。这里的 draw 函数是按帧调用的,其中我有我所有的绘图代码。

我编写了一个图像序列器,从图像索引返回相应的图像。

void draw()
{
sequence.getFrameForTime(getCurrentElapsedTime()).draw(0,0); //get current time returns time in float and startson application start
}

按键时,我从第一个图像 [0] 开始序列,然后继续。因此,每次我按下一个键时,它都必须从 [0] 开始,这与上面的代码不同,它基本上使用 currentTime%numImages 来获取帧(这不是图像的起始 0 位置)。

我想写一个自己的计时器,基本上每次按下键时都可以触发,以便时间始终从 0 开始。但在这样做之前,我想问一下是否有人对此有更好/更容易的实现想法?

编辑
为什么我不只使用计数器?我的 ImageSequence 中也有帧速率调整。

Image getFrameAtPercent(float rate)
{
float totalTime = sequence.size() / frameRate;
float percent = time / totalTime;
return setFrameAtPercent(percent);
}
int getFrameIndexAtPercent(float percent){
if (percent < 0.0 || percent > 1.0) percent -= floor(percent);
    return MIN((int)(percent*sequence.size()), sequence.size()-1);
}
void draw()
{
    sequence.getFrameForTime(counter++).draw(0,0); 
}
void OnKeyPress(){ counter = 0; }

这还不够吗?

你应该做的是增加一个"currentFrame"作为float,并将其转换为int来索引你的帧:

void draw()
{
    currentFrame += deltaTime * framesPerSecond; // delta time being the time between the current frame and your last frame
    if(currentFrame >= numImages)
        currentFrame -= numImages;
    sequence.getFrameAt((int)currentFrame).draw(0,0);
}
void OnKeyPress() { currentFrame = 0; }

这应该可以优雅地处理具有不同帧速率的计算机,甚至可以在一台计算机上处理帧速率的变化。

此外,当您循环时,您不会跳过帧的一部分,因为减法的其余部分将被保留。