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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With