Skip to content

Instantly share code, notes, and snippets.

@chasestarr
Created April 5, 2016 18:36
Show Gist options
  • Save chasestarr/d3baa1112ffc9cff7453249a8c3e2976 to your computer and use it in GitHub Desktop.
Save chasestarr/d3baa1112ffc9cff7453249a8c3e2976 to your computer and use it in GitHub Desktop.
///////////// Main Tab:
Mover m;
Attractor a;
void setup() {
size(400, 400);
background(0);
m = new Mover(100, 100);
a = new Attractor(200, 200);
}
void draw() {
background(0);
PVector force = a.attract(m);
m.applyForce(force);
m.update();
m.display();
a.applyForce(force);
m.checkEdges();
a.display();
a.update();
}
////////// Attractor tab:
class Attractor {
float mass;
PVector location;
PVector velocity;
PVector acceleration;
float G;
Attractor(float xLoc, float yLoc) {
location = new PVector (xLoc, yLoc);
//all of your variables need values! just like location, initialize acceleration and velocity
// two lines below added by Mr. Chase
acceleration = new PVector(0,0);
velocity = new PVector(0,0);
mass = random(1, 20);
G = 0.4;
}
void applyForce(PVector force) {
PVector f = PVector.div(force, mass);
acceleration.add(f);
}
void update() {
velocity.add(acceleration);
location.add(velocity);
acceleration.mult(0);
}
PVector attract(Mover m) {
PVector force = PVector.sub(location, m.location);
float distance = force.mag();
distance = constrain(distance, 5.0, 25.0);
force.normalize();
float strength = (G * mass * m.mass) / (distance * distance);
force.mult(strength);
return force;
}
//Display function added by Mr. Chase
void display(){
ellipse(location.x, location.y, 10,10);
}
void checkEdges(){
if(location.x > width){
velocity.x *= -1;
} else if(location.x < 0){
velocity.x *= -1;
}
if(location.y > height){
velocity.y *= -1;
} else if(location.y < 0){
velocity.y *= -1;
}
}
}
///////// Mover tab:
class Mover {
PVector location;
PVector velocity;
PVector acceleration;
float mass;
ArrayList<PVector> history;
Mover(float xLoc, float yLoc) {
location = new PVector(xLoc, yLoc);
velocity = new PVector(0, 0);
acceleration = new PVector(0, 0);
mass = random(1, 6);
history = new ArrayList<PVector>();
}
void applyForce(PVector force) {
PVector f = PVector.div(force, mass);
acceleration.add(f);
}
void display() {
stroke(0);
fill(150);
ellipse(location.x, location.y, 20*mass, 20*mass);
for (int i = 0; i< history.size(); i++) {
PVector current = history.get(i);
fill(255, 100, 100, i * 20);
ellipse(current.x, current.y, 20*mass, 20*mass);
}
}
void update() {
velocity.add(acceleration);
location.add(velocity);
acceleration.mult(0);
PVector v = new PVector(location.x, location.y);
history.add(v);
if (history.size() > 20) {
history.remove(0);
}
}
void checkEdges(){
if(location.x > width){
velocity.x *= -1;
} else if(location.x < 0){
velocity.x *= -1;
}
if(location.y > height){
velocity.y *= -1;
} else if(location.y < 0){
velocity.y *= -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment