C++ 在经过时间C+之后做某事+;SFML 2

C++ 在经过时间C+之后做某事+;SFML 2,c++,visual-studio-2010,sfml,visual-c++-2010,C++,Visual Studio 2010,Sfml,Visual C++ 2010,我在SFML中有一个时钟和计时器,它测量秒数。我正试图让下一个动作在经过一定的秒数后发生(特别是4秒),这是我的代码 #include "stdafx.h" #include "SplashScreen1.h" using namespace std; void SplashScreen1::show(sf::RenderWindow & renderWindow) { sf::Clock clock; sf::Time elapsed = clock.get

我在SFML中有一个时钟和计时器,它测量秒数。我正试图让下一个动作在经过一定的秒数后发生(特别是4秒),这是我的代码

    #include "stdafx.h"
#include "SplashScreen1.h"

using namespace std;

void SplashScreen1::show(sf::RenderWindow & renderWindow)
{
    sf::Clock clock;
    sf::Time elapsed = clock.getElapsedTime();

    sf::Texture splash1;
    sf::SoundBuffer buffer;
    sf::Sound sound;

    if(!buffer.loadFromFile("sounds/splah1.wav"))
    {
        cout << "Articx-ER-1C: Could not find sound splah1.wav" << endl;
    }

    sound.setBuffer(buffer);

    if(!splash1.loadFromFile("textures/splash1.png"))
    {
        cout << "Articx-ER-1C: Could not find texture splash1.png" << endl;
    }

    sf::Sprite splashSprite1(splash1);

    sound.play();
    renderWindow.draw(splashSprite1);
    renderWindow.display();

    sf::Event event;

    while(true)
    {
        while(renderWindow.pollEvent(event))
        {
            //if(event.type == sf::Event::EventType::KeyPressed
            if(elapsed.asSeconds() >= 4.0f)
            {
                //|| event.type == sf::Event::EventType::MouseButtonPressed)
                //|| event.type == sf::Event::EventType::Closed
                return;
            }

            if(event.type == sf::Event::EventType::Closed)
                renderWindow.close();
        }
    }
}
#包括“stdafx.h”
#包括“SplashScreen1.h”
使用名称空间std;
void SplashScreen1::show(sf::RenderWindow和RenderWindow)
{
sf:时钟;
sf::经过的时间=clock.getElapsedTime();
sf::1;
sf::声音缓冲区;
sf::声音;
如果(!buffer.loadFromFile(“sounds/splah1.wav”))
{

CUT

浮点比较不能如此精确。<代码>=4.0F 几乎不可能是真的。试试<代码> > <代码> < /p> < p>如果不能因为某种原因让SFML定时器工作,可以考虑使用ctime(time .h)。< /p>

#包括
/* ... */
time_t beginT=时间(NULL),endT=时间(NULL);
while(renderWindow.pollEvent(事件)){
if(difftime(endT,beginT)<4.0f){
endT=时间(空);
}
否则{
beginT=时间(空);
endT=时间(空)
/*做4秒钟后的事情*/
}
/* ... */
}

简单解释一下,您将endT设置为当前时间,直到它与之前设置的beginT相差整整4秒。

您的代码现在看起来很好,只是您应该更新循环中的已用变量(从时钟读取)

目前,您只需读取一次,并将该静态值与4进行多次比较

时间类型表示时间点,因此是静态的

你的代码应该是

...
while(renderWindow.pollEvent(event)) 
{
    elapsed = clock.getElapsedTime(); 
    // Rest of the loop code
    ...
}

你确定你想要4秒吗?不仅仅是在4秒过去的时候?嗯,我希望返回值在4秒之后出现,我不确定我是否理解你的问题。你现在的代码只有在if语句经过4秒之后才会运行(如果其二进制表示形式与if语句中的表示形式完全相同(相同的数字可以并且将在浮点中具有不同的二进制表示形式)),如果3.9999秒或4.00001秒已经过去,那么我想你想要的是>=4.0秒是的,我真的不在乎它是否正好是4秒,我确实尝试了>=4.0秒,但它不起作用。在这种情况下,代码肯定有不止一个问题。使用Ctime也是一个很好的解决方案
...
while(renderWindow.pollEvent(event)) 
{
    elapsed = clock.getElapsedTime(); 
    // Rest of the loop code
    ...
}