Billiards
by djwelsh
HTML
<script src="http://www.davidjohnwelsh.com/djw-js/DJWVisualVector.min.js"></script>
<canvas id="c" width="400" height="400"></canvas>
<canvas id="_c" width="120" height="80"></canvas>
<canvas id="_c2" width="100" height="100"></canvas>
<div id="debug"></div>
CSS
#c {
outline: 1px dashed #ccc;
width: 420px;
height: 420px;
margin: 10px;
}
#debug {
position: fixed;
right: 0px;
top: 0px;
width: 120px;
}
JavaScript
//Element stuff
var main_canvas,
main_ctx;
//Dimensions of canvas
var canvas_width, canvas_height;
//Store the collidibles, including the cueball
var objects = [];
//Size of universe in notional units. For now, 1nu = 1px (no zoom).
var universe = {
leftWall : 0,
rightWall : 400,
topWall : 0,
bottomWall : 400
};
//Position of the mouse on the canvas.
var mouse = {
x : 0,
y : 0
};
//Called every frame
function draw() {
main_ctx.clearRect(0,0,canvas_width,canvas_height);
//Main map
drawTable(main_ctx);
requestAnimationFrame(draw);
}
function drawTable(context) {
//Draw table edges
context.strokeStyle = "#ccc";
context.strokeRect(
universe.leftWall,
universe.topWall,
(universe.rightWall - universe.leftWall),
(universe.bottomWall - universe.topWall)
);
//Draw dummies
for (var i = 0; i < objects.length; i++) {
objects[i].updatePosition(context);
}
}
/*********************************/
/* CLASSES ***********************/
/*********************************/
function CueBall(obj) {
this.x = obj.x;
this.y = obj.y;
this.vx = 0;
this.vy = 0;
this.size = obj.size;
this.maxSpeed = 5;
this.speed = 0;
this.strokeStyle = "#333";
this.fillStyle = "#ccc";
this.id = "ball_" + (Math.random() * 10000);
}
//Calculate where we were, what our velocity is, and where we thus should be next. Calls draw() function after calculation.
CueBall.prototype.updatePosition = function (context) {
//New vx/vy is a vector based on mouse position relative to ship
//For stability we can change ship xy to half canvas w and h
var V_DirectionOfCueBall = new Vector({
x : mouse.x - this.x,
y : mouse.y - this.y
});
var N_DirectionOfCueBall = V_DirectionOfCueBall.normalize();
//Calculate speed based on distance of mouse from ship
var...