Collision Detection
HTML
<script src="http://calebevans.me/projects/jcanvas/resources/jcanvas/jcanvas.min.js"></script>
<canvas id="canvas" width='150' height="150"></canvas>
<div id="timer">0.00ms</div>
CSS
#canvas {
border: 1px solid black;
}
JavaScript
var cv = $("canvas");
var width = 150,
height = 150,
radius = 10,
rwidth = width - radius,
rheight = height - radius,
buffer = 2;
var x = 10,
y = 10,
paddlex = 300,
paddley = 350;
function ball(x, y, dx, dy, color) {
this.x = x;
this.y = y;
this.velo = [dx, dy];
this.color = color;
this.wallCollide = function() {
(this.x + this.velo[0] >= rwidth || this.x + this.velo[0] <= radius) ? this.velo[0] = -this.velo[0]: this.velo[0];
if (this.y + this.velo[1] >= rheight || this.y + this.velo[1] <= radius) {
this.velo[1] = -this.velo[1]
} else {
if (this.x > paddlex && this.x < (paddlex + 100)) {
if (this.y + this.dy >= paddley && this.y + this.dy < paddley + 20) {
this.dy = -this.dy;
}
}
}
};
this.ballCollide = function(balli) {
if (Math.abs((this.x) - (balli.x)) < (2 * radius - buffer)) {
if (Math.abs((this.y) - (balli.y)) < (2 * radius - buffer)) {
var tmpX = this.velo[0];
var tmpY = this.velo[1];
this.velo[0] = balli.velo[0];
this.velo[1] = balli.velo[1];
balli.velo[0] = tmpX;
balli.velo[1] = tmpY;
}
}
};
this.move = function() {
circle(this.x, this.y, this.color);
this.x += this.velo[0];
this.y += this.velo[1];
this.wallCollide();
}
}
function rect() {
cv.drawRect({
fillStyle: "black",
x: paddlex,
y: paddley,
width: 100,
height: 10,
fromCenter: false
})
}
function clear() {
cv.clearCanvas()
}
function circle(x, y, color) {
cv.drawArc({
fillStyle: color,
x: x,
y: y,
radius: radius
})
}
var ball1 = new ball(10, 50, 0.1, 0.2, 'green');
var ball2 = new ball(20, 10, 0.23, 0.11, 'red');
var ball3 = new ball(30, 35, 0.09, 0.24, 'blue');
var ball4 = new ball(40, 60, 0.18, 0.22, 'purple');
var ballArr = [];
ballArr.push(ball1);
ballArr.push(ball2);
ballArr.push(ball3);
ballArr.push(ball4);
function draw() {
clear();
for (var i = 0; i <...