Removing and re-adding elements to a vector

220 views Asked by At

Hi i'm somewhat new with c++ and openframeworks and I'm trying to get my program running more smooth by erasing the element from the vector when it goes out of the screen. At the moment as the time goes on it still gets slower and slower. I'm breaking my head over this. If you have any idea how I could improve this.

bool isDead(Particle &p) {
    if (p.position.x > ofGetWindowWidth() || p.position.x == -1 || p.position.y > ofGetWindowHeight() || p.position.y == -1) {
        return true;
    }
    else {
        return false;
    }
}
//--------------------------------------------------------------
void ofApp::setup() {


    ofSetFrameRate(60);
    ofEnableAlphaBlending();
    ofBackground(ofColor::black);

    for (int i = 0; i < 50; i++) {
        Particle p;
        p.setup(ofVec2f(ofRandom(ofGetWindowWidth() * 0.45, ofGetWindowWidth() * 0.55), ofRandom(ofGetWindowHeight() * 0.45, ofGetWindowHeight() * 0.55)));
        particles.push_back(p);
    }

    beat1.load("beat1.wav");
    beat2.load("beat2.wav");
    beat3.load("beat3.wav");

    fftSmooth = new float[8192];

    for (int i = 0; i < 8192; i++) {
        fftSmooth[i] = 0;
    }

    bands = 128;
    beat1.setVolume(0.2);
    beat2.setVolume(0.2);
    beat3.setVolume(0.2);
}
//--------------------------------------------------------------
void ofApp::update() {

    ofSoundUpdate();

    float * value = ofSoundGetSpectrum(bands);
    for (int i = 0; i < bands; i++) {
        fftSmooth[i] *= 0.2f;
        if (fftSmooth[i] < value[i]) {
            fftSmooth[i] = value[i];
        }
    }

    ofRemove(particles, isDead);

    for (Particle& p : particles) {
        if (!p.isActive) {
            p.position = ofVec2f(ofRandom(ofGetWindowWidth() * 0.45, ofGetWindowWidth() * 0.55), ofRandom(ofGetWindowHeight() * 0.45, ofGetWindowHeight() * 0.55));
            p.isActive = true;
            return;
        }
        p.update();
    }



    if (isDead) {
        Particle p;
        p.setup(ofVec2f(0, 0));
        particles.push_back(p);
    }

}

//--------------------------------------------------------------
void ofApp::draw() {
    for (Particle& p1 : particles) {
        if (!p1.isActive) continue;


        bool foundConnection = false;
        //search for connections.
        for (Particle& p2 : particles) {
            if (!p2.isActive || p2.drawPosition == p1.drawPosition) continue;

            float distance = p1.drawPosition.distance(p2.drawPosition);

            for (int i = 0; i < bands; i++) {
                if (distance > 10 && distance < 50 * fftSmooth[i]) {
                    ofDrawLine(p1.drawPosition, p2.drawPosition);
                    foundConnection = true;
                }
            }
        }

        for (int i = 0; i < 50; i++) {
            p1.draw(-(fftSmooth[i] * 10));

        }
    }
}
0

There are 0 answers