orbits

by jcubed111

HTML

<canvas id="main"></canvas>

CSS

body{
    margin: 0;
    padding: 0;
    overflow: hidden;
}

JavaScript

var canvas = document.getElementById("main");
var ctx = canvas.getContext('2d');
var z = 10;

document.addEventListener('wheel', e => {
	z *= e.deltaY > 0 ? Math.sqrt(0.5) : Math.sqrt(2.0);
});

var planets = [];

class Planet{
	constructor(radius, mass, pos, vel, color = "#f00") {
    	this.radius = radius;
        this.mass = mass;
        this.pos = pos;
        this.vel = vel;
        this.color = color;
        this.startPos = _.clone(this.pos);
        this.startVel = _.clone(this.vel);
    }
    
    render(ctx) {
    	ctx.beginPath();
        ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI*2);
        ctx.fillStyle = this.color;
        ctx.fill();
    }
}

/*planets.push(new Planet(2, 10, {x:0, y:0, z:0}, {x:0, y:0, z:0}, "#00f"));
planets.push(new Planet(1, 2, {x:  15, y:0, z:0}, {x:0, y:  7, z:0}, "#f00"));
planets.push(new Planet(0.5, 0.01, {x:  18, y:0, z:0}, {x:0, y: 3, z:0}, "#600"));
planets.push(new Planet(1, 2, {x: -10, y:0, z:0}, {x:0, y: -7, z:0}, "#0f0"));
planets.push(new Planet(0.5, 0.01, {x: -13, y:0, z:0}, {x:0, y:  -1, z:0}, "#060"));
*/

planets.push(new Planet(2, 20, {x: -10, y:0, z:0}, {x:0, y: 5, z:0}, "#00f"));
planets.push(new Planet(2, 20, {x:  10, y:0, z:0}, {x:0, y: -5, z:0}, "#0ff"));
planets.push(new Planet(1, 0.01, {x:  20, y:0, z:0}, {x:0, y: 12, z:0}, "#f0f"));
planets.push(new Planet(1, 0.01, {x: -15, y:0, z:0}, {x:0, y: 21.7, z:0}, "#f00"));


// zero inertia
let totalInertia = { x: 0, y: 0, z: 0};
let totalMass = 0;
planets.forEach(p => {
	totalInertia.x += p.vel.x * p.mass;
	totalInertia.y += p.vel.y * p.mass;
	totalInertia.z += p.vel.z * p.mass;
    totalMass += p.mass;
});
planets.forEach(p => {
	p.vel.x -= totalInertia.x / totalMass;
	p.vel.y -= totalInertia.y / totalMass;
	p.vel.z -= totalInertia.z / totalMass;
});

function step(deltaT, planets) {
	for(let p0 = 0; p0 < planets.length; p0++) {
    	for(let p1 = p0+1; p1 < planets.length; p1++) {
        	// compute force caused on b by a
  			const a =...