我可以为SFML/C++中的精灵设置时间限制吗?

3

我希望在屏幕上显示一个带有时间限制的警告信息(例如在游戏中)。

我的意思是,是否可以使用SFML在屏幕上显示一个只持续10秒钟的精灵?如果是,那么该如何实现?


是的,这是可能的。 - Martin Sand
你能解释一下怎么做吗? - Atefeh Mosafer
1
在精灵显示时存储当前时间。在其显示期间,在运行时循环中将当前时间与开始时间+时间限制进行比较。- 如果您想使其更通用,则必须使用具有到期时间和相应操作对的队列(例如可以由std :: function存储),该队列在运行时循环中进行检查。 - Scheff's Cat
2个回答

0
尝试像这样做:
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;

然后,只需使用

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

0

是的,这是可能的。最简单的方法是使用 sf::Clock 类:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接