Reputation: 51
I am making a game and can detect collisions. I need to now resolve them. What I want is the overlap x and y so that I can negate it. Shapes to get overlaps for. Circle & Circle. Circle & Rectangle. Note Rotation isn't needed.
There are some answers on stack overflow but none of them are what I want. I simply need overlap x and y and thats it.
Upvotes: 1
Views: 446
Reputation: 461
I remember struggling about this a few years ago while making one of my first games that involved a little physics. I couldn't find anything about it on internet so I made my own algorithm.
You can find it here in the function AABB::detectCollision()
. This function detects the overlap and the side of collision between 2 AABBs. I know, it's C++ and not JS but I'm sure you'll be able to "translate" it to JS.
Keep in mind that detecting collisions without taking into account the velocity of the 2 objects will never be extremely precise and will not work at high speeds.
For circles, it's much more simple.
Let's say you have 2 intersecting circles : A "fixed" one A
and a moving one B
.
The overlap between 2 circles is computed by calculating the distance between them and substracting the sum of their radius to it :
overlap = magnitude(A.pos - B.pos) - (A.radius + B.radius)
And the collision normal (direction towards which the collision needs to be resolved) is computed by normalizing the delta between the 2 circles :
direction = normalize(B.pos - A.pos) // An arrow pointing from A to B
And you move B
out of A
by adding to the position of B
the direction scaled by the overlap.
B.position += direction * overlap
Upvotes: 1