Pregunta

I have a clock and timer in SFML and it measures seconds. I'm trying to make the next action happen after a certain amount of seconds elapsed ( specifically 4) Here's my code

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

It does nothing after 4 seconds. I believe I'm gathering the elapsed time incorrectly. I know my return is working because I tried it with mouse input and it worked fine.

¿Fue útil?

Solución

Your code seems fine now, except that you should update your elapsed variable inside the loop (read it from your clock).

Currently your just reading it once, and comparing that static value to 4 a lot of times.

The time type represents a point in time, and is hence static.

Your code should be;

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

Otros consejos

Floating-point comparisons cannot be made so exactly. == 4.0f can almost never be true. Try >=.

If you can't get the SFML timer to work for some reason, you can consider doing it using ctime (time.h).

#include <ctime>
/* ... */
time_t beginT = time(NULL), endT = time(NULL);
while(renderWindow.pollEvent(event)) {

  if(difftime(endT, beginT) < 4.0f) {
    endT = time(NULL);
  }
  else {
    beginT = time(NULL);
    endT = time(NULL)

    /* do the after-4-seconds-thingy */
  }

  /* ... */
}

Briefly explained, you set endT to the current time until it differs a full 4 seconds from the previously set beginT.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top