Created
October 11, 2016 13:59
-
-
Save drguildo/1eb266c97570224589a985c5829f8b5b to your computer and use it in GitHub Desktop.
The Nature of Code - Exercise 2.3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Mover[] movers = new Mover[4]; | |
void setup() { | |
size(800, 320); | |
for (int i = 0; i < movers.length; i++) { | |
movers[i] = new Mover(random(0.1, 5), random(0, width), random(0, height)); | |
} | |
} | |
void draw() { | |
background(255); | |
PVector wind = new PVector(0.01, 0); | |
PVector gravity = new PVector(0, 0.1); | |
for (int i = 0; i < movers.length; i++) { | |
Mover m = movers[i]; | |
float edgeForceScale = 0.0002; | |
PVector leftForce = new PVector(abs(width - m.location.x) * edgeForceScale, 0); | |
PVector rightForce = new PVector(-(m.location.x * edgeForceScale), 0); | |
PVector topForce = new PVector(0, abs(height - m.location.y) * edgeForceScale); | |
PVector bottomForce = new PVector(0, -(m.location.y * edgeForceScale)); | |
movers[i].applyForce(leftForce); | |
movers[i].applyForce(rightForce); | |
movers[i].applyForce(topForce); | |
movers[i].applyForce(bottomForce); | |
movers[i].applyForce(wind); | |
movers[i].applyForce(gravity); | |
movers[i].update(); | |
movers[i].display(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Mover { | |
PVector location; | |
PVector velocity; | |
PVector acceleration; | |
float mass; | |
Mover(float m, float x, float y) { | |
mass = m; | |
location = new PVector(x, y); | |
velocity = new PVector(0, 0); | |
acceleration = new PVector(0, 0); | |
} | |
void applyForce(PVector force) { | |
PVector f = PVector.div(force, mass); | |
acceleration.add(f); | |
} | |
void update() { | |
velocity.add(acceleration); | |
location.add(velocity); | |
acceleration.mult(0); | |
} | |
void display() { | |
stroke(0); | |
fill(128, 198); | |
ellipse(location.x, location.y, mass*16, mass*16); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment