Key Press, add new vector particles and display them on screen


I am a beginner trying my best to figure out and modify the particle example at the bottom of the vector tutorial here so when I press a key a new particle is added to the vector and the total count of particles are drawn on screen in different starting positions, moving in random directions.

So far the only change I’ve made is to remove the code that removes the particle after it disappears on screen. It seems that now on key press a new particle is added to the vector but when it loops through in the draw function only one particle is shown on screen. I expect it to draw all the particles that have been added and see them moving in a random direction but maybe that’s the problem and they are overlapping? If so, how do I set each particle to have a random starting position on screen.

Really confused here and any advice is very much appreciated. I’m sure it’s something very straightforward but to be honest I’ve been trying desperately to figure it out for hours now.


#pragma once
#include "ofMain.h"
// create the particle class in the header for brevity
class Particle{
        pos.set( 0, 0, 0 );
        vel.set( ofRandom(-5,5), ofRandom(-4,-8), 0);
    void update(){
        pos += vel;
        vel.y += .1;
    void draw(){
    ofPoint pos;
    ofVec3f vel;
class ofApp : public ofBaseApp{
    void setup();
    void update();
    void draw();
    void keyPressed(int key);
    void keyReleased(int key);
    void mouseMoved(int x, int y);
    void mouseDragged(int x, int y, int button);
    void mousePressed(int x, int y, int button);
    void mouseReleased(int x, int y, int button);
    void windowResized(int w, int h);
    void dragEvent(ofDragInfo dragInfo);
    void gotMessage(ofMessage msg);
    // declare the vector of particles
    vector<Particle> particles;


#include "ofApp.h"
// write our boolean remove function
bool shouldRemove(Particle &p){
    if(p.pos.y > ofGetHeight() )return true;
    else return false;
void ofApp::setup(){
void ofApp::update(){
    for(int i = 0; i < particles.size(); i++){
void ofApp::draw(){
    ofTranslate( ofGetWidth()/2, ofGetHeight()/2);
    for(int i = 0; i < particles.size(); i++){
void ofApp::keyPressed(int key){
    particles.push_back( Particle() );

Thank you

Just to say that I don’t understand your problem, the code you posted works for me: (1.3 KB)

1 Like