Created
March 13, 2017 15:16
-
-
Save XiaohanYa/b772ae2226145b5e62a9107f5b5bce35 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 moon = []; | |
var earth; | |
function setup() { | |
createCanvas(800, 500); | |
background(0); | |
for (var i = 0; i < 3; i++) { | |
moon.push(new Particle(random(width), random(height), random(0.1, 3))); // (x,y,mass) | |
moon[i].vel.y = random(0.5, 1.2); | |
} | |
earth = new Particle(width / 2, height / 2, 15); // (x,y,mass) | |
} | |
function draw() { | |
background(0); | |
// earth.pos.x = mouseX; | |
// earth.pos.y = mouseY; | |
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); | |
moon[a].update(); | |
moon[a].display(); | |
} | |
earth.update(); | |
earth.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.mass = m; | |
this.rad = 2 * this.mass ; | |
} | |
applyForce(f) { | |
f.div(this.mass); | |
this.acc.add(f); | |
} | |
applyAttraction(other) { | |
var force = p5.Vector.sub(other.pos, this.pos); | |
force.mult(0.005); | |
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); | |
stroke(255); | |
fill(255, 100); | |
ellipse(0, 0, this.rad * 2, this.rad * 2); | |
pop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment