JavaScript: Collision detection

jack moore picture jack moore · Mar 13, 2010 · Viewed 101.7k times · Source

How does collision detection work in JavaScript?

I can't use jQuery or gameQuery - already using prototype - so, I'm looking for something very simple. I am not asking for complete solution, just point me to the right direction.

Let's say there's:

<div id="ball"></div>
and
<div id="someobject0"></div>

Now the ball is moving (any direction). "Someobject"(0-X) is already pre-defined and there's 20-60 of them randomly positioned like this:

#someobject {position: absolute; top: RNDpx; left: RNDpx;}

I can create an array with "someobject(X)" positions and test collision while the "ball" is moving... Something like:

for(var c=0; c<objposArray.length; c++){
........ and code to check ball's current position vs all objects one by one....
}

But I guess this would be a "noob" solution and it looks pretty slow. Is there anything better?

Answer

Husky picture Husky · Sep 4, 2011

Here's a very simple bounding rectangle routine. It expects both a and b to be objects with x, y, width and height properties:

function isCollide(a, b) {
    return !(
        ((a.y + a.height) < (b.y)) ||
        (a.y > (b.y + b.height)) ||
        ((a.x + a.width) < b.x) ||
        (a.x > (b.x + b.width))
    );
}

To see this function in action, here's a codepen graciously made by @MixerOID.