2014-01-22 19 views
0

我現在正在試驗事件並試圖通過窗口作爲參數來改變場景(菜單到級別和水平到其他級別),但我的主要問題是,該程序沒有采取我的關鍵事件。我基本上從here拿到了代碼,併爲場景變化添加了一個視圖線。現在,Change函數被註釋掉,直到我可以找出爲什麼keyevent沒有被註冊。SFML - KeyEvents不能正常工作

#include <SFML/Graphics.hpp> 
void Change(sf::RenderWindow& rwindow); 
int main() 
{ 
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!"); 
    sf::CircleShape shape(100.f); 
    shape.setFillColor(sf::Color::Green); 

    while (window.isOpen()) 
    { 
     sf::Event event; 
     while (window.pollEvent(event)) 
     { 
      if (event.type == sf::Event::Closed){ 
       window.close(); 
      } 

      if(event.type == sf::Event::KeyPressed){ 
       if(event.key.code == sf::Keyboard::Space){ 
       window.clear(); 
       sf::CircleShape shape(70.f); 
       shape.setFillColor(sf::Color::Red); 
       //Change(window); 
       } 
      } 
     } 

     window.clear(); 
     window.draw(shape); 
     window.display(); 
    } 

    return 0; 
} 

void Change(sf::RenderWindow& rwindow){ 
    rwindow.clear(); 
    sf::CircleShape shape(70.f); 
    shape.setFillColor(sf::Color::Red); 
} 
+0

你是說這個形狀永遠不會改變它的顏色嗎?你有沒有調試過你的代碼?把一個特定的地點放置一個斷點,看看是否被調用?您不應該在隨機位置清除或繪圖,而應遵循以下邏輯:計算物理位置和更新位置,清除屏幕,繪製實體,顯示在屏幕上。 – Lukas

回答

0

基本上你這樣做是:

int main() { 
    int x = 1; 
    if (true) { int x = 2; } 
    std::cout << x; 
    return 0; 
} 

This code will always output 1。爲什麼?因爲if聲明中的x與打印的聲明不一樣! Google 可變範圍如果您的書架上沒有好書。

在代碼中,你有三個不同的shape變量:第一個你main的開始,第二次在if聲明,並在Change功能第三位。

而不是創建一個新的變量,你需要始終使用相同的。這裏有一種方法:

#include <SFML/Graphics.hpp> 

void Change(sf::CircleShape& shape); 
void Unchange(sf::CircleShape& shape); 

int main() 
{ 
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!"); 
    sf::CircleShape shape(100.f); 
    shape.setFillColor(sf::Color::Green); 

    while (window.isOpen()) 
    { 
     sf::Event event; 
     while (window.pollEvent(event)) 
     { 
      if (event.type == sf::Event::Closed){ 
       window.close(); 
      } 

      if(event.type == sf::Event::KeyPressed){ 
       if(event.key.code == sf::Keyboard::Space){ 
        Change(shape); 
       } 
      } 

      if(event.type == sf::Event::KeyReleased){ 
       if(event.key.code == sf::Keyboard::Space){ 
        Unchange(shape); 
       } 
      } 

     } 

     window.clear(); 
     window.draw(shape); 
     window.display(); 
    } 

    return 0; 
} 

void Change(sf::CircleShape& shape){ 
    shape.setRadius(70.f); 
    shape.setFillColor(sf::Color::Red); 
} 

void Unchange(sf::CircleShape& shape){ 
    shape.setRadius(100.f); 
    shape.setFillColor(sf::Color::Green); 
}