简体   繁体   English

在 SFML 中将生命周期 function 添加到 object

[英]Adding a lifetime function to an object in SFML

I am currently trying to create an object which after a certain period of time appears on screen.我目前正在尝试创建一个 object,它会在一段时间后出现在屏幕上。 The object appears but it does so immediately and is visible. object 出现,但它立即出现并且可见。 How would I change this so the object starts off screen and then moves onscreen after a certain interval of time?我将如何更改此设置,以便 object 从屏幕开始,然后在一定时间间隔后移动到屏幕上? In my header file I have the function:在我的 header 文件中,我有 function:

void time(sf::Time 15, int x_pos, int y_pos){
// spawn = true;
body-> setPosition(x_pos,y_pos);
}

and in the cpp file I have:在 cpp 文件中我有:

Game(int size,std::string title){
    win = new sf::RenderWindow(sf::VideoMode(size,size),title);
    powerup = new Powerup(-1,-1);
int x_pos = rand() % 100 + 1;
int y_pos = rand() % 100 + 1;
}
void run(){
    while (win->isOpen()){
        Event e;
        while (win->pollEvent(e)){
            if(e.type == Event::Closed){
                win->close();
            }

I have gotten thus far but don't know how to ensure that it is right.到目前为止,我已经取得了进展,但不知道如何确保它是正确的。

I decided to make the object handle itself via update function, you can always change it and manage it from while window.isOpen() or wherever else you would like to.我决定通过update function 使 object 自行处理,您可以随时更改它并从while window.isOpen()或您想要的任何其他地方进行管理。

Object Object

Object{
public:
    Object(sf::Vector2f position) : object(sf::Vector2f(20.f,20.f)){//object size = {20, 20}
        is_visible = false;
        object.setPosition(position);
    }
    void update(float deltaTime){
        if(!is_visible){//hidden        
            spawnTimer += deltaTime;
            if(spawnTimer>=10.f)//10 seconds
                setVisible(true);
        }
    }
    void setVisible(bool& is_visible){
        this->is_visible = is_visible;
    }
    const bool& isVisible() const {
        return is_visible;
    }
private:
    float spawnTimer;
    bool is_visible;
    sf::RectangleShape object;
};

Main主要的

main(){
    sf::RenderWindow window(sf::VideoMode(size, size), title);
    sf::Clock clock;
    float deltaTime = 0.f;
    Object myObject(sf::Vector2f(100.f,100.f);
    while(window.isOpen()){
        deltaTime = clock.restart().asSeconds();
        //skipped events handling since it is irrelevant    
        myObject.update(deltaTime);
        
        //rendering
        window.clear();
        if(myObject.isVisible)//if is visible draw it
            //draw myObject
        //...
        window.display();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM