C ++ SFML显示多个图像

时间:2017-01-23 20:04:03

标签: c++ image animation textures sfml

我正在尝试制作一个程序,以便它显示一个颅骨张开的图像,然后以1秒的间隔关闭。当我运行它时,它只显示" skullmouthopen"。我不知道我哪里出错了,我没有收到任何错误信息。只是一个小病毒为我的朋友恶作剧:)

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

1 个答案:

答案 0 :(得分: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();
}

另请注意,根据图形的大小,您可能希望在一个纹理中同时具有纹理/精灵/帧。