【问题标题】:SFML Player movement issueSFML 播放器移动问题
【发布时间】:2017-01-25 20:23:13
【问题描述】:

我正在 SFML 库中制作游戏,并且正在尝试使 Player 移动。我不知道为什么按下右箭头键时它没有移动。

游戏.cpp

#include "Game.h"

Game::Game()
{
windowWidth = 800;
windowHeight = 600;
}

Game::~Game()
{
}

void Game::Start()
{
window.create(sf::VideoMode(windowWidth, windowHeight), "Game");
window.setFramerateLimit(60);

while (window.isOpen())
{
    sf::Event e;
    while (window.pollEvent(e))
    {
        if (e.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
        {
            window.close();
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
        {
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
        {
            character.MoveRight();
        }
    }

    character.SetPosition(windowWidth, windowHeight);
    character.UpdatePosition();
    Draw();
}
}

void Game::Draw()
{
window.clear();

character.DrawPlayer(window);

window.display();
}

播放器.cpp

#include "Player.h"

Player::Player()
{
player.setSize(sf::Vector2f(200, 50));
player.setFillColor(sf::Color::White);

playerX = 300;
playerY = 300;
playerSpeed = 5.f;
}

Player::~Player()
{
}

void Player::MoveRight()
{
playerX += playerSpeed;
}

void Player::SetPosition(float windowWidth, float windowHeight)
{
playerX = windowWidth / 2 - 100;
playerY = windowHeight - 50;
}

void Player::UpdatePosition()
{
player.setPosition(playerX, playerY);
}

void Player::DrawPlayer(sf::RenderWindow &window)
{
window.draw(player);
}

欢迎告诉我我应该在我的代码中进行哪些更改。

【问题讨论】:

    标签: c++ sfml


    【解决方案1】:

    所以这是你的主循环中发生的事情:

       character.SetPosition(windowWidth, windowHeight); // Put this line to get a start location
       while (window.isOpen())
       {
            sf::Event e;
            while (window.pollEvent(e))
            {
                // your code...
            }
    
            character.SetPosition(windowWidth, windowHeight); // <---- Remove this line
            character.UpdatePosition();
            Draw();
        }
    }
    

    您不断将字符位置设置为windowWidthwindowHeight,因此无论您调用character.MoveRight(),您总是在重置位置。

    我还建议添加一些用于处理输入控件的内容,甚至可以将它们放在 Player 中的 update 方法中,并为您的事件循环删除它们,因为它可以运行多次并会命中您的 @ 987654327@多次。

    最后一点建议是查看 SFML 的时钟,这样您就可以根据时间而不是帧速率平滑地移动角色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 2013-04-05
      • 2013-10-31
      • 2015-03-20
      • 1970-01-01
      • 2019-07-20
      • 2018-02-18
      相关资源
      最近更新 更多