Particles with Springs

testApp.h

#pragma once

#include "ofMain.h"

class Particle : public ofVec2f {
public:
    ofVec2f vel,acc;
       
    void update() {
        vel += acc;
                
        *this += vel;
        acc.set(0,0);
        
        if (x<0 || x>ofGetWidth()) vel.x=-vel.x;
        if (y<0 || y>ofGetHeight()) vel.y=-vel.y;
    }
};

class Spring {
public:
    Particle *a, *b;
    float len;
    
    Spring(Particle &a, Particle &b) {
        this->a = &a;
        this->b = &b;
        len = 100; //a.distance(b);
    }
    
    void update() {
        float dist = a->distance(*b);
        ofVec2f dir = *b - *a;
        dir.normalize();
        dir *= (dist-len)/100;
        a->vel += dir;
    }
    
};

class testApp : public ofBaseApp {
public:
    void setup() {
        ofSetFrameRate(60);
        ofBackground(0);
        ofSetWindowShape(500, 500);
        ofEnableAlphaBlending();
    }
    
    void update() {
        for (int i=0; i<springs.size(); i++) {
            springs[i].update();
        }
        
        for (int i=0; i<particles.size(); i++) {
            particles[i].update();
        }
    }
    
    void draw() {
        for (int i=0; i<particles.size(); i++) {
            Particle &p = particles[i];
            ofSetColor(0,0,150,150);
            ofCircle(p.x, p.y, 35);
        }        
        
        for (int i=0; i<springs.size(); i++) {
            Particle &a = *springs[i].a;
            Particle &b = *springs[i].b;
            ofSetColor(255);
            ofLine(a,b);
        }
        
        if (ofGetFrameNum()%10==0) {
            springs.clear();
            for (int i=0; i<particles.size(); i++) {
                Particle &a = particles[i];
                for (int j=0; j<particles.size(); j++) {
                    Particle &b = particles[j];
                    if (a.distance(b)<150) {
                        springs.push_back(Spring(a,b));
                    }
                }
            }
        }
    }

    void keyPressed(int key) {
        Particle p;
        p.set(ofRandomWidth(), ofRandomHeight());
        particles.push_back(p);
    }
    
    vector<Particle> particles;
    vector<Spring> springs;
    
};


Comments