SFML精灵在没有按键的情况下不断重复

时间:2016-01-22 21:15:57

标签: c++ visual-c++ sfml

这段代码应该让我的精灵表改变它的图像部分, 虽然它确实如此,但它并没有完全响应任何按键,但在没有任何键盘输入的情况下,它会从一个精灵快速变换到另一个精灵。

以下是导致此类错误或错误的代码:

#include <SFML\Graphics.hpp>
#include <iostream>

int main() {

sf::RenderWindow window;
window.create(sf::VideoMode(1000, 600), "Ludus");
sf::Texture mTexture;
sf::Sprite  mPlayer;

enum Move { Left, Right};
sf::Vector2i source(1, Left);

if (!mTexture.loadFromFile("Image.png"))
{
    std::cout << "error" << std::endl;
};

mPlayer.setTexture(mTexture);

while (window.isOpen()) {

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
        source.y = Right;
    }
    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
        source.y = Left;
    }

    source.x++;
    if (source.x * 97 >= 291)
        source.x = 0;

    mPlayer.setTextureRect(sf::IntRect(source.x * 97, source.y * 91, 97, 91));
    window.draw(mPlayer);
    window.display();
    window.clear(sf::Color(255, 255, 255, 0));
}
return 0;
}

更新

添加名称为floats的三个frameCounterswitchFrameframeSpeed将其修复如下,

    frameCounter += frameSpeed * clock.restart().asSeconds();
    if (frameCounter >= switchFrame) {
        frameCounter = 0;
        source.x++;
    if (source.x * 97 >= mTexture.getSize().x)
        source.x = 0;
    }

frameCounter被赋值为0,switchFrame 100和frameSpeed 650。

0 个答案:

没有答案