2017-12-02 5 views
0

느린 A 또는 D을 조금 움직이면 멈추고 다시 움직이며 계속됩니다.SFML 화면의 움직임은 내가 최근 SFML을 배우기 시작하고 나는 그것을 쉽게해야하기 때문에 탁구 클론을 만들고 싶어하지만 코딩을하는 동안이 문제에있어

#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

#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

귀하의 문제는 당신이 입력 처리 전략 (폴링 이벤트 대 현재 상태를 확인하는) 것입니다

#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.

또한이 방법을 지금 구현 한 방법은 큐에 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

감사 남자 :

은 당신이 일반적으로 수행 할 수 있습니다 것은 그들 반복하는 동안 이벤트를 확인하다 그것! –