2017-01-23 85 views
0

我想製作一個程序,以便它顯示一張頭顱的圖像,然後以1秒的間隔關閉它。當我運行它時,它只顯示「skullmouthopen」。我不確定我出錯的地方,我沒有收到任何錯誤消息。只是一個小小的病毒惡作劇爲我的朋友:)C++ SFML顯示多個圖像

#include <SFML/Graphics.hpp> 
#include <iostream> 
#include <chrono> 
#include <thread> 
using namespace sf; 

void f() 
{ 
    std::this_thread::sleep_for(std::chrono::seconds(1)); 
} 


int main() 
{ 
    RenderWindow gameDisplay(VideoMode(800, 600), "Oops"); 

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

     Texture texture; 
     if (!texture.loadFromFile("o_cdf78ec6b8037e00-0.png")) 
     { 
      // error... 
     } 

     Texture texture2; 
     if (!texture.loadFromFile("o_cdf78ec6b8037e00-1.png")) 
     { 
      // error... 
     } 

     sf::Sprite skullmouthclosed; 
     skullmouthclosed.setTexture(texture); 
     skullmouthclosed.setPosition(300, 200); 

     Sprite skullmouthopen; 
     skullmouthopen.setTexture(texture2); 
     skullmouthopen.setPosition(300, 200); 

     gameDisplay.draw(skullmouthclosed); 
     gameDisplay.display(); 
     f();  
     gameDisplay.draw(skullmouthopen); 
     gameDisplay.display(); 
     f(); 
    } 

    return 0; 
} 
+0

你在相同的紋理上調用'loadFromFile'兩次。此外,該代碼不應該在循環中,你不需要兩個精靈。 **投票結束**。 – LogicStuff

+0

如果圖像具有透明部分,或者您打算稍後移動它們,則缺少'gameDisplay.clear();'。 – LogicStuff

回答

0

對於動畫,你通常會想要一些更新計數器或計時器。另外 - 正如評論中提到的 - 儘量避免(重新)加載或複製主循環中的紋理,因爲這會減慢一切。

你最有可能想嘗試這樣的事:

// Create and load our textures and sprites 
sf::Texture texOpen, texClosed; 
texOpen.loadFromFile("mouthOpen.png"); 
texClosed.loadFromFile("mouthClosed.png"); 
sf::Sprite mouthOpen(texOpen); 
sf::Sprite mouthClosed(texClosed); 

// Timing related objects (see below) 
sf::Clock clock; 
sf::Time passedTime; 

while(window.isOpen()) 
    // Event handling would happen here 

    // Accumulate time 
    passedTime += clock.restart(); 

    // Subtract multiples of two seconds (one animation cycle) 
    while (passedTime > sf::seconds(2)) 
     passedTime -= sf::seconds(2); 

    // Clear the window 
    window.clear(); 

    // Decide what to draw based on the time in our interval 
    if (passedTime <= sf::seconds(1)) 
     window.draw(mouthOpen); 
    else 
     window.draw(mouthClosed); 

    // Display the window 
    window.display(); 
} 

另外要注意的是,根據圖形的大小,你可能希望有兩個紋理/精靈/幀的一個紋理。

+0

謝謝你們。我根本不知道你必須寫兩次紋理的名字! :) –