Forces + Attractors




Processing code:

Mover [] mover= new Mover[50]; Attractor a; void setup() { size(800, 800); noCursor(); smooth(); for (int i=0; i< mover.length; i++) { mover[i] =new Mover(int(random(0, 1))); } a = new Attractor(); } void draw() { noStroke(); fill(80, 100, 120, 50); rect(0, 0, width, height); //Draw Attractor a.display(); //Draw Movers for (int i=0; i< mover.length; i++) { //Movers are repeled by each other for (int j = 0; j < mover.length; j++) { if (i != j) { PVector repelforce = mover[j].repel(mover[i]); mover[i].applyForce(repelforce); } } //Movers are attracted to the Attractor PVector attractforce = a.attract(mover[i]); mover[i].applyForce(attractforce); mover[i].move(); mover[i].display(); } } class Attractor { float ellipseRad; PVector location; float g; int resize; Attractor() { ellipseRad=20; g=10; } // Attraction force PVector attract(Mover mover) { PVector force = PVector.sub(location, mover.location); // distance from attractor to mover float distance = force.mag();// length of vector distance = constrain(distance, 5.0, 25.0); force.normalize(); float strength = (g * ellipseRad * ellipseRad) / (distance * distance); force.mult(strength); return force; } void display() { location = new PVector(mouseX, mouseY); noStroke(); fill(100, 200, 100, 50); if (ellipseRad > 19) { resize = 0; } else if (ellipseRad < 0) { resize = 1; } if (resize == 1) { ellipseRad += random(.2, .25); } else if ( resize== 0) { ellipseRad -=random(.2, .25); } ellipse(location.x, location.y, ellipseRad*2, ellipseRad*2); } } class Mover { float radius, topspeed, resize; PVector location, velocity, acceleration, noff; int dir; float g; Mover(int _resize) { radius=random(4, 6); resize=_resize; topspeed=2; location=new PVector(random(width), random(height)); velocity=new PVector(0, 0); acceleration=new PVector(random(-5, 5), random(-5, 5)); g=-radius*2; } void display() { noStroke(); fill(100, 200, 100); ellipse(location.x, location.y, radius, radius); } void move() { location.add(velocity); velocity.add(acceleration); acceleration.mult(.25); velocity.limit(topspeed); } void applyForce(PVector f) { acceleration.add(f); } PVector repel(Mover mover) { PVector force = PVector.sub(location, mover.location); float distance = force.mag(); force.normalize(); float strength = (g * radius * radius) / (distance * distance); force.mult(strength); return force; } }

One Comment

  1. Pingback: Angular Motion + Oscillation | SMD @ ITP

Leave a Reply