我正在开始使用 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();
}
}
它目前的作用是在按键后稍作停顿,然后正常进行,但是我怎样才能做到在开始时没有那么小的停顿。
最佳答案
不要在按键事件上移动对象,而是设置一个变量来指示它应该移动的方向和速度。然后,在按键释放事件中,将速度重置为 0。然后从事件处理部分单独处理移动,并通过这些变量和某种计时系统的组合进行调节。
关于c++ - SFML 键盘输入延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14301703/