我最近开始学习SFML,我想制作一个Pong克隆,因为它应该很容易,但我在编码时遇到了这个问题:
蝙蝠运动非常迟钝,当我按 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);
}
答案 0 :(得分:0)
您的问题是您是输入处理策略(轮询事件与检查当前状态)。
此外,你现在实现这一点的方式,意味着如果在队列中有 - 只是假设 - 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;
}
}
(注意这是来自内存,因此未经测试,可能包括拼写错误。)