Created
March 13, 2017 15:05
-
-
Save XiaohanYa/026e757f78e19f3c9c59baefcc41b096 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var earth = []; | |
var moon = []; | |
function setup() { | |
createCanvas(800, 500); | |
background(0); | |
for (var i = 0; i < 3; i++) { | |
moon.push(new Particle(random(100, 200), random(150, 250), random(1, 3))); | |
moon[i].vel.y = random(1, 2); | |
} | |
earth[0] = new Particle(random(width), random(height), random(5, 15)); // (x,y,mass) | |
earth[0].vel.x = random(0, 0.1); | |
earth[1] = new Particle(width / 2, height / 2, random(15, 30)); // (x,y,mass) | |
earth[1].vel.x = random(0, 0.1); | |
} | |
function draw() { | |
background(0); | |
for (var a = 0; a < moon.length; a++) { | |
for (var b = 0; b < moon.length; b++) { | |
moon[a].applyAttraction(moon[b]); | |
} | |
moon[a].applyAttraction(earth[0]); | |
//moon[a].applyAttraction(earth[1]); | |
moon[a].update(); | |
moon[a].display(); | |
} | |
for (var a = 0; a < moon.length; a++) { | |
for (var b = 0; b < moon.length; b++) { | |
moon[a].applyAttraction(moon[b]); | |
} | |
moon[a].applyAttraction(earth[0]); | |
moon[a].applyAttraction(earth[1]); | |
moon[a].update(); | |
moon[a].display(); | |
} | |
earth[0].applyAttraction(earth[1]); | |
earth[0].update(); | |
earth[0].display(); | |
//earth[1].update(); | |
earth[1].display(); | |
} | |
"use strict"; | |
class Particle { | |
constructor(x, y, m) { | |
this.pos = createVector(x, y); | |
this.vel = createVector(0, 0); | |
this.acc = createVector(0, 0); | |
this.rad = 2; | |
this.mass = m; | |
//this.c=color(random(255),random(255),random(255)); | |
} | |
applyForce(f) { | |
f.div(this.mass); | |
this.acc.add(f); | |
} | |
applyAttraction(other) { | |
var force = p5.Vector.sub(other.pos, this.pos); | |
var distance = force.mag(); | |
force.normalize(); | |
force.mult((0.5 * this.mass * other.mass) / (distance * distance)) | |
this.acc.add(force); | |
} | |
update() { | |
this.vel.add(this.acc); // vel = vel + acc; | |
this.pos.add(this.vel); // pos = pos + vel; | |
this.acc.mult(0); // acceleration has to be reset after being applied! *** | |
} | |
display() { | |
push(); | |
translate(this.pos.x, this.pos.y); | |
// beginShape(); | |
// curveVertex(0, 0); | |
// curveVertex(0, 0); | |
// endShape(); | |
noStroke(); | |
fill(255); | |
ellipse(0, 0, this.rad * 2 * this.mass, this.rad * 2 * this.mass); | |
pop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment