每次按键时从零开始计数

时间:2013-01-29 05:18:15

标签: c++ algorithm events

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

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

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开始。但在此之前,我想问一下是否有人有更好/更容易实现的想法?

EDIT
为什么我不使用只是一个柜台? 我也在我的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);
}

2 个答案:

答案 0 :(得分:1)

void draw()
{
    sequence.getFrameForTime(counter++).draw(0,0); 
}

void OnKeyPress(){ counter = 0; }

这有什么理由不够吗?

答案 1 :(得分: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; }

这应该可以优雅地处理具有不同帧率的机器,甚至可以在一台机器上更改帧速率。

此外,当你继续循环时,你不会跳过帧的一部分,因为保留了剩余的减法。