SFML没有正确移动精灵

时间:2017-05-04 00:30:24

标签: c++ sfml

SFML没有移动精灵超过1个像素(即使被保持)。它还会在释放正在按下的箭头键时将精灵移回其设定位置。

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();
     }
}

1 个答案:

答案 0 :(得分:1)

在评论中提到您始终设置位置时,您还要在每个帧中重新创建精灵,因此即使您没有调用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();
 }
}