Timer and multiple object spawns

Hi, I’ve been tackling with a very simple idea but can’t figure it out…
I want to display several rectangles and start scaling them sequentially
(every x seconds, one rectangle appears and starts scaling up) to give a flying illusion (as if I’m flying through these rectangles).

Rectangle.cpp

Rectangle::Rectangle() {
        
    }

void Rectangle::update() {
    speed += 0.01;
}

void Rectangle::draw() {

    ofPushMatrix();
    
    ofSetRectMode(OF_RECTMODE_CENTER);
    ofNoFill();
    ofSetColor(ofColor::white);
    ofSetLineWidth(3.0);
    
    ofTranslate(ofGetWindowWidth()/2, ofGetWindowHeight()/2);
    
    ofScale(speed, speed);
    
    ofDrawRectangle(0, 0, 300, 300);
    
    ofPopMatrix();
}

ofApp.cpp

    void ofApp::draw(){
    
    myTimer = ofGetElapsedTimeMillis();
    
    if (myTimer > 2000) {
        
        rects[k].update();
        rects[k].draw();
        k++;
        myTimer = 0;
    }
    
    ofLog() << myTimer;

}

It looks like the rectangle will only run update and draw for one frame every two seconds since myTimer is being reset to 0 as soon as they do. Take out the line

myTimer = 0;

to see a rectangle animate. Simplest way to do this for all of them is to make a bool for each rectangle to tell it whether or not it should be animating. Try doing something like this to see them iterating like you want:

Rectangle.h

bool started;

Rectangle.cpp

Rectangle::Rectangle(){
    started = false;
 }

ofApp.h

bool run;

ofApp.cpp

void ofApp::setup(){
    run = false;
}

void ofApp::update(){
    myTimer = ofGetElapsedTimef();

    if ((int)myTimer % 2 == 0){
        if (!run){
            k++;
            rects[k].started = true;
            run = true;
        }
    }else
        run = false;

    for (int i = 0; i < rects.size(); i++){
        if (rects[i].started)
            rects[i].update();
    }
}

void ofApp::draw(){
    for (int i = 0; i < rects.size(); i++){
        if (rects[i].started)
            rects[i].draw();
    }
}

Depending on what else you want to do with the rectangles, there are better ways to do it. For example, if you just need them to animate once through and then disappear once they “pass” the camera, I would store them in a vector and create a new one every 2 seconds, destroying them when they go off screen. That way you don’t have to worry about resetting them.

1 Like

Thanks a lot tabularasa1992; your suggestion is close to the solution and I see your point about using vectors.
However I still can’t succeed at creating the rectangles one after another, every x seconds. In your code and mine, every x seconds a bunch of rectangles appear and start scaling together…

Yup, sorry I made a mistake in my code. I just edited it to check if it’s already been run every two seconds. Should work now.

1 Like

Thank you very much tabularasa1992 for your time and intellect, this worked perfectly :slightly_smiling:

1 Like