c++ - SFML 没有正确移动 Sprite

标签 c++ sfml

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/

相关文章:

c++ - 使用 Clang、libc++ 和 c++11 制作 SFML2 应用程序。对 SFML 库的 undefined reference

c++ - 管道通信 C++

c++ - 我如何测量 C 代码的运行时间比较?

c++ - 使用 C++ 从 XML 文件返回 char* 以外的数据类型时出错

c++ - 一次包含已在 main.obj 中定义的 .h 函数

C++ Box2D - 单独放置时不受重力影响的动态物体

c++ - 如何从单独的线程控制SFML窗口?

c++ - 将 SFML RenderWindow 传递给类

c++ - 跟踪 C++ 类中的更改

c++ - 添加 QListWidgetItem 到 QListWidget