SFML Sprite 运动未正确更新

SFML Sprite movement not updating correctly

我正在创建一个简单的游戏,使用游戏状态。 我有一个 gameLoop() 方法调用 running() 方法,它包含切换状态,它工作正常。 这是 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() 方法绘制精灵并移动它:

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

}

问题是精灵只是原地移动,当按下 A 或 D 时,从 std::cout 获得的输出如下:

机芯功能正常,因为在别处测试过。我认为我正在正确更新或以错误的方式初始化某些东西,但我无法弄清楚。

您应该在循环外的地方声明 myTextureandmySprite,只要它们应该停留就可以。 目前,您在每次迭代中都会再次创建它们,这对性能不利(特别是 myTexture.loadFromFile("res/img/player.png");)。游戏还重置了变换(位置、旋转等)

我不熟悉 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);

    }

希望对您有所帮助