2016-05-31 12 views
1

我想每次按下空格按鈕時重複RectangleShape rect1,但不是這樣做,它似乎只是刪除我的向量Vec的rect1對象我釋放空間鍵。我無法弄清楚爲什麼,有人幫助我嗎?無法創建使用向量push_back代碼的對象的副本

這裏是我的代碼:

int main() { 

class shape { 
public: 
    RectangleShape rect1; 
}; 

shape getShape; 
getShape.rect1.setSize(Vector2f(100, 100)); 
getShape.rect1.setFillColor(Color(0, 255, 50, 30)); 

RenderWindow window(sf::VideoMode(800, 600), "SFML Game"); 
window.setFramerateLimit(60);   

window.setKeyRepeatEnabled(false); 

bool play = true; 
Event event;  
while (play == true) { 

    while (window.pollEvent(event)) { 
     if (event.type == Event::Closed) { 
      play = false; 
     } 
    } 

    window.clear(); 

    vector <shape> Vec; 

    if (Keyboard::isKeyPressed(Keyboard::Space)) { 
     Vec.push_back(getShape); 
    } 

    for (int i = 0; i < Vec.size(); ++i) { 
     window.draw(Vec[i].rect1); 
    } 

    window.display(); 
} 

window.close(); 
return 0; 
} 

回答

1

您需要將外循環的載體,否則你創建一個新的空單,每次:

int main() { 
    // If you need to use this class in something other than main, 
    // you will need to move it outside of main. 
    class shape { 
    public: 
     RectangleShape rect1; 
    }; 

    // But in this particular case you don't even need a class, 
    // why not just use RectangleShape? 
    shape getShape; 
    getShape.rect1.setSize(Vector2f(100, 100)); 
    getShape.rect1.setFillColor(Color(0, 255, 50, 30)); 

    RenderWindow window(sf::VideoMode(800, 600), "SFML Game"); 
    window.setFramerateLimit(60);   

    window.setKeyRepeatEnabled(false); 

    bool play = true; 
    Event event; 
    std::vector<shape> Vec; // Put your vector here! 

    // play is already a bool, so you don't need == true 
    while (play) { 
     while (window.pollEvent(event)) { 
      if (event.type == Event::Closed) { 
       play = false; 
      } 
     } 

     window.clear(); 

     if (Keyboard::isKeyPressed(Keyboard::Space)) { 
      Vec.push_back(getShape); 
     } 

     for (int i = 0; i < Vec.size(); ++i) { 
      window.draw(Vec[i].rect1); 
     } 

     window.display(); 
    } 

    window.close(); 
    return 0; 
} 
+0

噢,我明白現在非常感謝幫助! – SSLukeY

+0

你不想在這裏使用'Keyboard :: isKeyPressed' ...只是打印你的矢量的大小,你會明白爲什麼。改用事件。 – Hiura