Keypress上的SFML动画仅移动一帧

时间:2018-04-17 17:56:43

标签: animation timer sfml elapsedtime

我想在按下方向键时让我的动画循环显示两个图像。目前,它在每个按键上切换图像。我一直在寻找教程,并了解我需要某种计时器来测量每个帧时间,但到目前为止我尝试在我的代码中实现的所有内容都失败了所以我只是发布了我现在正在运行的代码。

有人可以向我解释如何实施这个吗?

    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
}

1 个答案:

答案 0 :(得分:0)

首先,当按下正确的键时,我只会拨打' 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看起来有点时髦。请查看https://en.sfml-dev.org/forums/index.php?topic=10913.0但我真的推荐本指南:https://github.com/SFML/SFML/wiki/Source:-AnimatedSprite