Created
March 5, 2017 10:48
-
-
Save XiaohanYa/1c8a446151ea9911cd19b4c887fe3edf to your computer and use it in GitHub Desktop.
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
var earth; | |
var moon; | |
function setup() { | |
createCanvas(1000, 600); | |
background(0); | |
earth = new Earth(0, 0, random(30, 50)); | |
moon = new Moon(100, 100, random(3, 5)); | |
} | |
function draw() { | |
background(0, 30); | |
push(); | |
translate(width / 2, height / 2); | |
//attraction between earth and moon | |
var G = p5.Vector.sub(earth.pos, moon.pos); | |
G.limit(5); | |
G.mult(earth.eGravity * moon.mGravity); | |
moon.applyAttraction(G); | |
moon.update(); | |
moon.display(); | |
earth.update(); | |
earth.display(); | |
pop(); | |
} | |
"use strict" | |
class Earth { | |
constructor(x, y, rad) { | |
this.pos = createVector(x, y); | |
this.vel = createVector(0, 0); // *** | |
this.acc = createVector(0, 0); | |
this.rad = 20; | |
this.airRad = 25; | |
this.eGravity = rad * 0.001; | |
} | |
applyForce(f) { | |
f.div(this.mass); | |
this.acc.add(f); | |
} | |
update() { | |
this.pos.x = cos(frameCount * 0.01) * 39; | |
this.pos.y = sin(frameCount * 0.01) * 39; | |
this.vel.add(this.acc); | |
this.pos.add(this.vel); | |
this.acc.mult(0); | |
} | |
display() { | |
push(); | |
translate(this.pos.x, this.pos.y); | |
noStroke(); | |
fill(0, 0, 255, 100); | |
ellipse(0, 0, this.rad * 2 * this.mass, this.rad * 2 * this.mass); | |
noFill(); | |
stroke(255, 10); | |
strokeWeight(5); | |
ellipse(0, 0, this.airRad * 2 * this.mass, this.airRad * 2 * this.mass); | |
pop(); | |
} | |
} | |
"use strict" | |
class Moon { | |
constructor(x, y, rad) { | |
this.pos = createVector(x, y); | |
this.vel = createVector(0, 0); // *** | |
this.acc = createVector(0, 0); | |
this.rad = 3; | |
this.mGravity = rad * 0.001; | |
} | |
applyAttraction(GRAVITY) { | |
GRAVITY.mult(this.mass / this.rad); | |
this.acc.add(GRAVITY); | |
} | |
applyForce(f) { | |
f.div(this.mass); | |
this.acc.add(f); | |
} | |
update() { | |
this.pos.x = cos(frameCount * 0.01) * 10; | |
this.pos.y = sin(frameCount * 0.01) * 10; | |
this.vel.add(this.acc); | |
this.pos.add(this.vel); | |
this.acc.mult(0); | |
} | |
display() { | |
push(); | |
translate(this.pos.x, this.pos.y); | |
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