Colliding Orbitals
by djwelsh
HTML
<canvas id="c" width="400" height="400"></canvas>
<div id="debug"></div>
CSS
#c {
outline: 1px solid #ccc;
width: 400px;
height: 400px;
margin: 10px;
}
#debug {
position: fixed;
right: 0px;
top: 0px;
width: 120px;
}
JavaScript
var GLOBAL_SPEED_SCALE = 0.025;
//Element stuff
var main_canvas,
main_ctx;
//Dimensions of canvas
var canvas_width, canvas_height;
var asteroids = [];
//Called every frame
function draw() {
main_ctx.clearRect(0,0,canvas_width,canvas_height);
//Draw the asteroids and the ship
drawStuff(main_ctx);
requestAnimationFrame(draw);
}
function drawStuff(context) {
context.strokeStyle = "#ccc";
context.beginPath();
context.arc(200, 200, 100, 0, Math.PI * 2, false);
context.stroke();
for (var i = 0; i < asteroids.length; i++) {
if (!asteroids[i].collided) {
asteroids[i].checkCollision();
}
}
for (var i = 0; i < asteroids.length; i++) {
asteroids[i].updatePosition(context);
asteroids[i].collided = false;
}
}
/*********************************/
/* CLASSES ***********************/
/*********************************/
function Vector (obj) {
this.x = obj.x;
this.y = obj.y;
}
Vector.prototype.magnitude = function () {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
Vector.prototype.normalize = function () {
var mag = this.magnitude();
if (mag === 0) mag = 0.0000001;
var normalizedX = this.x / mag;
var normalizedY = this.y / mag;
return new Vector({ x : normalizedX, y : normalizedY });
};
Vector.prototype.definedAngle = function () {
//Prevent division by zero
if (this.x == 0) this.x = 0.000001;
var angle = Math.PI / 2 + Math.atan(this.y / this.x);
if (this.x < 0) {
//Adjust for values greater than 180 degrees
angle += Math.PI;
}
return angle;
};
function Asteroid(obj) {
//This is where the particle currently is
this.x = obj.x;
this.y = obj.y;
//This stuff never changes, and is what lets us calculate where the particle should be
this.centerX = obj.centerX;
this.centerY = obj.centerY;
this.rad = obj.rad;
...