Created
June 4, 2013 21:32
-
-
Save captainbrosset/5709797 to your computer and use it in GitHub Desktop.
Pixel-perfect javascript 2D collision detection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
2d pixel-perfect collision detection | |
Requires that each object has a rectangular bounding box (simple x/y/w/h, no rotation) | |
and a bit mask (i.e. an array of lines and columns containing 0s for empty pixels and 1s for solid pixels). | |
On each frame of the animation, take all pairs of objects and | |
1. compare the bounding boxes | |
2. for those that collide, check for overlayed bits by creating a new mask that is the AND of the 2 sub-masks and check for 1s | |
*/ | |
// Example with a predefined (simplistic) pair of objects | |
var object1 = { | |
x: 0, | |
y: 0, | |
w: 8, | |
h: 4, | |
mask : [ | |
[0,0,0,1,1,0,0,0], | |
[0,0,1,1,1,1,0,0], | |
[0,1,1,1,1,1,1,0], | |
[1,1,1,1,1,1,1,1] | |
] | |
}; | |
var object2 = { | |
x: 8, | |
y: 2, | |
w: 8, | |
h: 4, | |
mask : [ | |
[0,1,1,1,1,0,0,0], | |
[0,1,1,1,1,0,0,0], | |
[0,1,1,1,1,0,0,0], | |
[1,1,1,1,1,1,1,1] | |
] | |
}; | |
function collide(o1, o2) { | |
var xs = [o1, o2].sort(function(a, b) {return o1.x - o2.x;}); | |
var ys = [o1, o2].sort(function(a, b) {return o1.y - o2.y;}); | |
// Do bounding boxes collide | |
if(xs[0].x + xs[0].w > xs[1].x && ys[0].y + ys[0].h > ys[1].y) { | |
// Create the collision bounding box | |
var cBounding = {}; | |
cBounding.x = xs[1].x; | |
cBounding.y = ys[1].y; | |
cBounding.w = Math.min(xs[0].x + xs[0].w, xs[1].x + xs[1].w) - cBounding.x; | |
cBounding.h = Math.min(ys[0].y + ys[0].h, ys[1].y + ys[1].h) - cBounding.y; | |
// Overlay the 2 masks within the collision bounding box and return as soon as a 1 is found | |
for(var x = 0; x < cBounding.w; x ++) { | |
for(var y = 0; y < cBounding.h; y ++) { | |
var bit1 = o1.mask[y + cBounding.y - o1.y][x + cBounding.x - o1.x]; | |
var bit2 = o2.mask[y + cBounding.y - o2.y][x + cBounding.x - o2.x]; | |
if(bit1 && bit2) { | |
return { | |
x : x + cBounding.x, | |
y : y + cBounding.y | |
}; | |
} | |
} | |
} | |
} | |
}; | |
console.log(collide(object1, object2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if the velocity of the player is greater than the size (width or height) of the box?