首页 > 解决方案 > 位置没有在事件c ++中更新

问题描述

我希望变量 curr_pos_x 和 curr_pos_y 保存播放器的更新值,但是每当我第二次按下任何上/下/左/下键时,位置设置为重置,然后根据单击的按钮进行更新。

while (window.isOpen())
{
    sf::Event event;
            
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
            window.close();
        }


        if (event.type == sf::Event::KeyPressed)
        {
            float curr_pos_x;
            float curr_pos_y;
            
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            {
                // move right...
                curr_pos_x = PLAYER_START_X + PLAYER_WIDTH;
                curr_pos_y = PLAYER_START_Y;
                player.setPosition(sf::Vector2f(curr_pos_x, curr_pos_y));
            }
            else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
                curr_pos_x = PLAYER_START_X - PLAYER_WIDTH;
                curr_pos_y = PLAYER_START_Y;
                player.setPosition(sf::Vector2f(curr_pos_x, curr_pos_y));
            }
            else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
                curr_pos_x = PLAYER_START_X;
                curr_pos_y = PLAYER_START_Y - PLAYER_HEIGHT;
                player.setPosition(sf::Vector2f(curr_pos_x, curr_pos_y));
            }
            else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){
                curr_pos_x = PLAYER_START_X;
                curr_pos_y = PLAYER_START_Y + PLAYER_HEIGHT;
                player.setPosition(sf::Vector2f(curr_pos_x, curr_pos_y));
            }
        }
    }
    window.clear(sf::Color::Black);
    window.draw(player);
    window.display();
}

标签: c++

解决方案


推荐阅读