Collision Detection
by djwelsh
HTML
<script src="http://www.davidjohnwelsh.com/djw-js/DJWVisualVector.min.js"></script>
<canvas id="djw-canvas" width="400" height="300"></canvas>
<div id="djw-options">
<label>
<input class="options-bounding" id="BoundingBox" type="checkbox" checked="checked" />Show bounding boxes
</label>
<label>
<input class="options-bounding" id="Radius" type="checkbox" checked="checked" />Show bounding circles
</label>
<hr />
<label>
<input class="options-intersection" id="rectRect" type="radio" name="intersect" checked="checked" />Rect to Rect
</label>
<label>
<input class="options-intersection" id="circleCircle" type="radio" name="intersect" />Circle to Circle
</label>
<label>
<input class="options-intersection" id="circlePolygon" type="radio" name="intersect" disabled="disabled" />Circle to Polygon
</label>
<label>
<input class="options-intersection" id="polygonPolygon" type="radio" name="intersect" disabled="disabled" />Polygon to Polygon
</label>
</div>
<div id="djw-debug"></div>
CSS
canvas {
outline: 1px solid #333;
}
label {
display: block;
}
JavaScript
var oO = {
ctx: null,
stop : false,
canvas: {
top: 0,
bottom: 300,
left: 0,
right: 400
},
options: {
drawBoundingBox: true,
drawCenterPoint: true,
drawRadius: true,
collisionMethod: {
rectRect: 0,
circleCircle: 1,
circlePolygon: 2,
polygonPolygon: 3
},
currentCollisionMethod: 0,
collide : true
},
shapeTotal : 0,
shapeIndex : 0,
shapes: {},
addShape : function (shape, obj) {
oO.shapeIndex++;
var id = shape + '_' + oO.shapeIndex;
oO.shapes[id] = obj;
return id;
},
redraw: function () {
if (oO.stop) return;
oO.ctx.clearRect(0, 0, 400, 300);
var dist = 0,
distX = 0,
distY = 0;
var c_bc = null,
c_bb = null;
//Update all shapes
for (var s in oO.shapes) {
oO.ctx.lineWidth = 0.5;
oO.ctx.fillStyle = '#ccc';
oO.ctx.strokeStyle = '#333';
var bb = oO.shapes[s].getBoundingBox();
var bc = oO.shapes[s].getBoundingCircle();
if ((bb.top < oO.canvas.top) || (bb.bottom > oO.canvas.bottom)) {
oO.shapes[s].dy *= -1;
}
if ((bb.left < oO.canvas.left) || (bb.right > oO.canvas.right)) {
oO.shapes[s].dx *= -1;
}
if (oO.options.currentCollisionMethod === oO.options.collisionMethod.rectRect) {
/**************************************/
/* COLLISION DETECTION (RECT to RECT) */
/**************************************/
//Run through shapes, flagging them if they are colliding with something
for (var c in oO.shapes) {
c_bb = oO.shapes[c].getBoundingBox();
//Don't compare a shape to itself
if...