Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Collision detection

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?

like image 479
jack moore Avatar asked Mar 13 '10 22:03

jack moore


People also ask

How do you perform collision detection?

If both the horizontal and vertical edges overlap we have a collision. We check if the right side of the first object is greater than the left side of the second object and if the second object's right side is greater than the first object's left side; similarly for the vertical axis.

What is JS collision?

In JavaScript, a collision occurs when two or more HTML elements collide. By default, when using a move event listener on an HTML element, it will not hit any other element on the screen. It will pass through the other elements in the DOM.

How do you detect 2D collisions?

The most basic way to approach this type of 2d collision detection is to utilize a concept known as Axis-aligned bounding box. Axis-aligned bounding box, or AABB, detects if two non-rotational polygons are overlapping each other.


1 Answers

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.

like image 55
Husky Avatar answered Sep 23 '22 08:09

Husky