2017-12-02 115 views
0

我最近开始学习SFML,我想作一个傍克隆,因为它应该是容易的,但我得到了这个问题,而编码:SFML屏幕移动速度很慢

蝙蝠运动是非常laggy,当我请按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); 
} 

回答

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

(注意,这是从内存,所以未经测试,可能包括错别字。)

+0

感谢的人我它! –