首先,我已经在 SFML 论坛上问过这个问题,但他们无能为力,他们实际上复制了我的代码并且它运行良好,即使有人与我使用相同的操作系统(Windows 8)
我目前正在阅读 SFML Game Development 书,在第一章中,当介绍运动时,我遇到了一些问题,我在窗口中心生成了一个白色圆圈,现在如果我按下任何方向箭头,圆圈就会继续在另一个方向,直到我按下它,然后它恢复正常,水平和垂直是分开的。
示例:我开始“游戏”,按下,圆圈一直向下,我按住,圆圈静止,我松开,它一直向下,我按下,它停止,现在它对两个键都有正常响应,它左右会再次发生,它在初始错误后得到修复,但我想知道如何删除它
#include <SFML/Graphics.hpp>
using namespace sf;
class Game
{
public:Game();
void run();
private:
void processEvents();
void update(Time);
void render();
void handlePlayerInput(Keyboard::Key,bool);
bool mIsMovingUp, mIsMovingRight, mIsMovingLeft, mIsMovingDown;
float playerSpeed;
Time TimePerFrame;
private:
RenderWindow mWindow;
CircleShape mPlayer;
};
Game::Game():mWindow(VideoMode(640, 480), "SFML Application"),mPlayer(), playerSpeed(20.f), TimePerFrame(seconds(1.f / 60.f))
{
mPlayer.setRadius(20.f);
mPlayer.setPosition(220.f, 220.f);
mPlayer.setFillColor(Color::White);
}
void Game::handlePlayerInput(Keyboard::Key key, bool isPressed)
{
if (key == Keyboard::W || key == Keyboard::Up)
mIsMovingUp = isPressed;
else if (key == Keyboard::S || key == Keyboard::Down)
mIsMovingDown = isPressed;
else if (key == Keyboard::A || key == Keyboard::Left)
mIsMovingLeft = isPressed;
else if (key == Keyboard::D || key == Keyboard::Right)
mIsMovingRight = isPressed;
}
void Game::run()
{
Clock clock;
Time timeSinceLastUpdate = Time::Zero;
while (mWindow.isOpen())
{
processEvents();
timeSinceLastUpdate += clock.restart();
while (timeSinceLastUpdate > TimePerFrame)
{
timeSinceLastUpdate -= TimePerFrame;
processEvents();
update(TimePerFrame);
}
render();
}
}
void Game::processEvents()
{
Event event;
while (mWindow.pollEvent(event))
{
switch (event.type)
{
case Event::KeyPressed:
handlePlayerInput(event.key.code, true);
break;
case sf::Event::KeyReleased:
handlePlayerInput(event.key.code, false);
break;
case sf::Event::Closed:
mWindow.close();
break;
}
}
}
void Game::update(Time deltaTime)
{
Vector2f movement(0.f, 0.f);
if (mIsMovingUp)
movement.y -= playerSpeed;
if (mIsMovingDown)
movement.y += playerSpeed;
if (mIsMovingLeft)
movement.x -= playerSpeed;
if (mIsMovingRight)
movement.x += playerSpeed;
mPlayer.move(movement * deltaTime.asSeconds());
}
void Game::render()
{
mWindow.clear();
mWindow.draw(mPlayer);
mWindow.display();
}
int main()
{
Game game;
game.run();
}