SFML播放器移动问题

时间:2017-01-25 20:23:13

标签: c++ sfml

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

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

Player.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);
}

随时告诉我应该在代码中更改哪些内容。

1 个答案:

答案 0 :(得分:0)

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

   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内,并为事件循环删除它们,因为它可以运行多次,会多次点击character.MoveRight()

最后一些建议是关注SFML的时钟,因此您可以根据时间而不是帧速率平滑地移动角色。

相关问题