Home > other >  can i make a time limit for a sprite in sfml/cpp?
can i make a time limit for a sprite in sfml/cpp?

Time:09-16

I want to show a warning note on the screen with time-limit(for instance in a game).

I mean, is it possible to show up a sprite just for 10 sec with SFML? If yes, then how?

CodePudding user response:

Try smth like that:

public:
    warning(){
        _isVisible = true;
        _warn = sf::CircleShape(10.f);
        _warn.setFillColor(sf::Color::Red);
    }

    void checkTime(){
        if(_timeForWarn - _timer.getElapsedTime().asSeconds() <= 0){
            _isVisible = false;
        }
    }

    void RestartTime(){
        _timer.restart();
    }

    bool GetVisibility(){
        return _isVisible;
    }


    sf::CircleShape getWarnObj() const{
        return _warn;
    }

private:
    sf::CircleShape _warn;
    bool _isVisible = false;
    sf::Clock _timer;
    float _timeForWarn = 3.f;

And then, just use

    w.checkTime();
    if(w.GetVisibility()){
        window.draw(w.getWarnObj());
    }    

CodePudding user response:

Yes it's possible. Simplest way would be to use the sf::Clock class:

//Do have in mind sf::Clock starts counting from creation of object, use reset function to start it from anytime you want.
class dissapearingOBject
{
public:
    sf::RectangleShape rect; // the visual part of the object
    sf::Clock timer; //the timer
    int dissTime; // the time to dissapear at in milliseconds
    
    dissapearingOBject(int time = 10000) : dissTime(time)
    {
        
    }
    
    dissapearingOBject()
    {
        
    }

    void resetTimer()
    {
        timer.restart();
    }
    
    int getTimer()
    {
        return timer.getElapsedTime().asMilliseconds();
    }
    
    void draw(sf::RenderWindow &window)
    {
        if (getTimer() < dissTime)
        {
            window.draw(rect);
        }
    }
};
  • Related