【问题标题】:SFML screen movement is slowSFML 画面移动缓慢
【发布时间】:2017-12-03 20:10:00
【问题描述】:

我最近开始学习 SFML,我想制作一个 Pong 克隆,因为它应该很容易,但我在编码时遇到了这个问题:

蝙蝠移动非常缓慢,当我按下 AD 时,它会移动一点然后停止然后再次移动并继续。

#include <SFML/Graphics.hpp>
#include "bat.h"
int main()
{
int windowWidth=1024;
int windowHeight=728;
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "SFML window");

bat Bat(windowWidth/2,windowHeight-20);



while (window.isOpen())
{

    sf::Event event;
    while (window.pollEvent(event))
    {

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))

                Bat.batMoveLeft();

            else if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))

            Bat.batMoveRight();

            else if (event.type == sf::Event::Closed)
            window.close();
    }


    window.clear();

Bat.batUpdate();

window.draw(Bat.getShape());

    window.display();
}


return 0;
}

bat.h

#ifndef BAT_H
#define BAT_H
#include <SFML/Graphics.hpp>

class bat
{
private:
           sf::Vector2f position;

    float batSpeed = .3f;

    sf::RectangleShape batShape;

public:
    bat(float startX, float startY);

    sf::FloatRect getPosition();

    sf::RectangleShape getShape();

    void batMoveLeft();

    void batMoveRight();

    void batUpdate();



 };

#endif // BAT_H

bat.cpp

    #include "bat.h"
using namespace sf;
bat::bat(float startX,float startY)
{
position.x=startX;

position.y=startY;

batShape.setSize(sf::Vector2f(50,5));
batShape.setPosition(position);

}
FloatRect bat::getPosition()
{
    return batShape.getGlobalBounds();
}

RectangleShape bat::getShape()
{
    return batShape;
}
void bat::batMoveLeft()
{
    position.x -= batSpeed;
}
void bat::batMoveRight()
{
    position.x += batSpeed;
}
void bat::batUpdate()
{
    batShape.setPosition(position);
}

【问题讨论】:

    标签: c++ sfml


    【解决方案1】:

    您的问题是您的输入处理策略(轮询事件与检查当前状态)。

    此外,您现在实施的方式意味着如果队列中有(仅假设)5 个事件,您将在两次绘制之间移动球棒 5 次。如果只有一个事件(例如“key down”),您将移动球棒一次。

    您通常想要做的是在迭代事件时检查事件:

    while (window.pollEvent(event)) {
        switch (event.type) {
            case sf::Event::Closed:
                window.close();
                break;
            case sf::Event::KeyDown:
                switch (event.key.code) {
                    case sf::Key::Left:
                        bat.moveLeft();
                        break;
                    // other cases here
                }
                break;
        }
    }
    

    (请注意,这是凭记忆进行的,未经测试,可能包含拼写错误。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      • 2022-07-16
      • 1970-01-01
      • 2017-05-22
      • 2015-03-20
      相关资源
      最近更新 更多