【问题标题】:C++ SFML Displaying Multiple ImagesC++ SFML 显示多个图像
【发布时间】:2017-06-08 10:51:17
【问题描述】:

我正在尝试制作一个程序,以便它显示一个头骨的图像,它的嘴张开,然后以 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;
}

【问题讨论】:

  • 你在同一个纹理上调用了两次loadFromFile。此外,该代码不应在循环中,并且您不需要两个精灵。 投票结束
  • 如果图像有透明部分,或者您打算稍后移动它们,您会错过gameDisplay.clear();

标签: c++ image animation textures sfml


【解决方案1】:

对于动画,您通常需要一些更新计数器或计时器。另外——正如 cmets 中提到的——尽量避免在你的主循环中(重新)加载或复制纹理,因为这会减慢一切。

你很可能想尝试这样的事情:

// 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();
}

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

【讨论】:

  • 谢谢大家。我根本不知道你必须写两次纹理的名称! :)
猜你喜欢
  • 2011-03-31
  • 2020-11-22
  • 1970-01-01
  • 2020-11-13
  • 2015-03-03
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多