【问题标题】:SFML Keyboard input delaySFML 键盘输入延迟
【发布时间】:2012-12-27 10:11:33
【问题描述】:

我开始使用 C++ 的 SFML 库,我已经来到了一个一切正常但不是我想要的方式的地方。

我的问题是,我怎样才能用键盘平稳地移动一个对象,而没有一点延迟?

#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>

using namespace sf;

const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;

int main(){
VideoMode VMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32);
RenderWindow screen(VMode, "Empty Window");
Event event;
Keyboard key;
Color screencolor(0,150,0);
Texture pietexture;
pietexture.loadFromFile("image.png");
Sprite pie(pietexture);
pie.setPosition(150,150);
screen.draw(pie);
screen.display();
bool on = true;
while(on){
    screen.clear(Color(0,255,0));
    while(screen.pollEvent(event)){
        if(event.type == Event::Closed){
            screen.close();
            on = false;
        }
        else if(event.type == Event::KeyPressed){
            if(key.isKeyPressed(Keyboard::Left)){
                pie.move(-10,0);
            }
            if(key.isKeyPressed(Keyboard::Right)){
                pie.move(10,0);
            }
            if(key.isKeyPressed(Keyboard::Up)){
                pie.move(0,-10);
            }
            if(key.isKeyPressed(Keyboard::Down)){
                pie.move(0,10);
            }

        }
    }
    screen.draw(pie);
    screen.display();
}

}

它目前的作用是在按键后稍作停顿,然后正常运行,但是我怎样才能在开始时没有那个小停顿。

【问题讨论】:

    标签: c++ keyboard sfml


    【解决方案1】:

    不要在按键事件上移动对象,而是设置一个变量来指示它应该移动的方向和速度。然后,在按键释放事件中,将速度重置为 0。然后与事件处理部分分开处理移动,由这些变量和某种计时系统的组合来调节。

    【讨论】:

      【解决方案2】:

      使用sf::Keyboard::isKeyPressed(key)实时轮询按键状态。根据经验,不要在需要高度响应界面的地方使用事件。

      您还需要一个计时机制来调节速度。有一个 sf::Clock 可以用于此目的。

      【讨论】:

        猜你喜欢
        • 2011-02-08
        • 1970-01-01
        • 1970-01-01
        • 2015-09-25
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        • 1970-01-01
        • 2014-08-21
        相关资源
        最近更新 更多