SFML 不会将 Sprite 移动超过 1 个像素(即使保持)。它还会在松开按住的箭头键时将 Sprite 移回其设定位置。
void Engine::mainLoop() {
//Loop until window is closed
while (window->isOpen()) {
processInput();
update();
sf::Sprite test;
sf::Texture texTest;
texTest.loadFromFile("img.png");
test.setTexture(texTest);
test.setPosition(50, 50);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up))
test.move(0, -1);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down))
test.move(0, 1);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left))
test.move(-1, 0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right))
test.move(1, 0);
window->clear(sf::Color::Black);
window->draw(test);
renderFrame();
window->display();
}
}
最佳答案
除了提到您始终设置位置的评论之外,您还在每一帧重新创建 Sprite ,因此即使您不调用 setPosition
附带说明一下,您还在每一帧加载纹理,这是非常低效的!
这应该是你想要的:
void Engine::mainLoop() {
sf::Sprite test;
sf::Texture texTest;
texTest.loadFromFile("img.png");
test.setTexture(texTest);
test.setPosition(50, 50);
//Loop until window is closed
while (window->isOpen()) {
processInput();
update();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up))
test.move(0, -1);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down))
test.move(0, 1);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left))
test.move(-1, 0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right))
test.move(1, 0);
window->clear(sf::Color::Black);
window->draw(test);
renderFrame();
window->display();
}
}
关于c++ - SFML 没有正确移动 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43771991/