Animation 按键上的SFML动画仅移动一帧

Animation 按键上的SFML动画仅移动一帧,animation,timer,sfml,elapsedtime,Animation,Timer,Sfml,Elapsedtime,当按下方向键时,我试图让动画在两个图像之间循环。目前,它会在每次按键时切换图像。我一直在看教程,了解到我需要某种计时器来测量每一帧的时间,但到目前为止我在代码中尝试实现的一切都失败了,所以我现在只发布我的代码 有谁能向我解释一下如何实施这一点吗 void Frog::up(sf::Event event) { sf::IntRect frogUpAnimation[iNumFrames]; frogUpAnimation[0] = sf::IntRect(13, 362,

当按下方向键时,我试图让动画在两个图像之间循环。目前,它会在每次按键时切换图像。我一直在看教程,了解到我需要某种计时器来测量每一帧的时间,但到目前为止我在代码中尝试实现的一切都失败了,所以我现在只发布我的代码

有谁能向我解释一下如何实施这一点吗

    void Frog::up(sf::Event event)
{
    sf::IntRect frogUpAnimation[iNumFrames];
    frogUpAnimation[0] = sf::IntRect(13, 362, 21, 23);
    frogUpAnimation[1] = sf::IntRect(46, 367, 21, 23);

    if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Up)
    {
        audio.frogjumpsound();
        frogSprite.move(0.0f, -55.0f);
        iScoreCounter = iScoreCounter + 10;
        iCurrentFrame++;
        if (iCurrentFrame >= iNumFrames) iCurrentFrame = 0;
        frogSprite.setTextureRect(frogUpAnimation[iCurrentFrame]);
    }
}



int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 800), "Frogger");
    window.setFramerateLimit(60);

    sf::Clock timer;
    float fFrameTime = 1.0f / 60.0f;
    float fElapsedTime;

    sf::Event event;

    Game game;
    Frog frog;
    Timer countdown;
    Text text;
    Audio gameaudio;

    gameaudio.music();

    while (window.isOpen())
    {
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                window.close();
            }

            if (event.type == sf::Event::KeyPressed)
            {
                game.processKeyPress(event.key.code);

            }

            frog.up(event);
            frog.down(event);
            frog.left(event);
            frog.right(event);

        } // Event loop

        countdown.gametime();

        fElapsedTime = timer.getElapsedTime().asSeconds();
        if (fElapsedTime > fFrameTime)
        {
            timer.restart();
        }

        //Update
        game.checkPads(&frog);
        game.checkWin();
        game.gameOver();
        frog.scorecounter(&countdown);
        frog.update(fElapsedTime);
        game.update(fElapsedTime);
        text.update(fElapsedTime);
        countdown.update(fElapsedTime);
        game.collision(&frog);

        // Drawing
        window.clear();
        window.draw(game);
        window.draw(frog);
        window.draw(countdown);
        window.draw(text);
        window.display();
    } // main loop
}

首先,我只会在按下正确的键时调用'frog.up()'、'frog.left()'等。否则,每次迭代可能调用4个函数,这些函数完全不起作用

if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right) {
    frog.right();
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) {
    frog.left();
}
至于你的计时器问题,你的fElapsedTime和fFrameTime看起来有点古怪。看一看,但我真的推荐这本指南: