SFML屏幕运动很慢

SFML screen movement is slow

本文关键字:运动 屏幕 SFML      更新时间:2023-10-16

我最近开始学习sfml,我想制作一个乒乓球,因为这应该很容易,但是我在编码时遇到了这个问题:

蝙蝠运动非常懒惰,当我按 a d 时,它会移动一点然后停止然后再次移动并继续。

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

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

此外,您现在就实施此操作的方式意味着,如果有 - 假设 - 队列中的5个事件,则您将在绘图之间移动蝙蝠5次。如果只有一个事件(例如"键向下"),您将一次移动蝙蝠。

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

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

(请注意这是来自内存,因此未经测试,可能包括错字。)