我正在使用游戏状态创建一个简单的游戏。
我有一个调用 running()
方法的 gameLoop()
方法,它包含切换状态,可以正常工作。
这是 gameLoop()
方法:
void Game::gameLoop()
{
while (window.isOpen()) {
Event event;
while (window.pollEvent(event)) {
if (event.type == Event::Closed){
window.close();
}
}
if (Keyboard::isKeyPressed(Keyboard::Escape)) {
window.close();
}
window.clear();
running(); //this calls the states
window.display();
}
running()
方法调用所有状态:
void Game::running()
{
switch (state)
{
//other cases here
case s_play:
play();
break;
default:
break;
}
}
然后 play()
方法绘制 Sprite 并移动它:
void Game::play()
{
Texture myTexture; //I've also tried to declare these outside the method
Sprite mySprite;
///////////Graphics
myTexture.loadFromFile("res/img/player.png");
mySprite.setTexture(myTexture);
//////////Movement
static sf::Clock clock;
float dt = clock.restart().asSeconds();
Vector2f move;
if (Keyboard::isKeyPressed(Keyboard::A))
{
move.x--;
}
std::cout << mySprite.getPosition().x << "\n";
}
if (Keyboard::isKeyPressed(Keyboard::D))
{
move.x++;
}
std::cout << mySprite.getPosition().x << "\n";
}
mySprite.move(move*300.0f*dt);
window.draw(mySprite);
}
问题是 Sprite 只是原地移动,当按下 A 或 D 时,从 std::cout 获得的输出如下:
机芯的功能有效,因为它在别处进行了测试。我认为我正在正确更新或以错误的方式初始化某些东西,但我无法弄清楚。
最佳答案
我不熟悉 SFML,所以我希望我在这里没有偏离基础,但是,请查看您的代码。在您的 play() 方法中,您创建了一个局部变量 move。从外观上看,move 包含 Sprite 的 x 和 y 坐标。由于您在 play() 方法中定义了移动,因此本地拷贝 每次您的代码运行 play() 方法时,都会在运行时在堆栈上创建此变量。然后你检查按键,以及 inc 或 dec 相应地移动。 move 需要在全局范围内,这样它就不会在您每次调用 play() 时都被重置。 当您将 myTexture 和 mySprite 移到函数 play() 之外时,您是正确的。您还应该将 move 移到 play() 方法之外。
像这样:
Texture myTexture; //I've also tried to declare these outside the method
Sprite mySprite;
Vector2f move;
void Game::play()
{
///////////Graphics
myTexture.loadFromFile("res/img/player.png");
mySprite.setTexture(myTexture);
//////////Movement
static sf::Clock clock;
float dt = clock.restart().asSeconds();
if (Keyboard::isKeyPressed(Keyboard::A))
{
move.x--;
}
std::cout << mySprite.getPosition().x << "\n";
}
if (Keyboard::isKeyPressed(Keyboard::D))
{
move.x++;
}
std::cout << mySprite.getPosition().x << "\n";
}
mySprite.move(move*300.0f*dt);
window.draw(mySprite);
}
希望对你有帮助
关于c++ - SFML Sprite 运动未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46196490/