Separating Axis Theorem: how to handle the rectangles overlapping stuck

319 views Asked by At

I have implemented a Separated Axis Theorem to manage translating and spinning rectangles collisions detection and response (the physics of the response might not be very accurate but nevermind, I'm good enough with it for now). However I struggle managing when two rectangles are stuck overlapping, or when one is stuck to the canvas edge: like on this gif

If anyone has the beginning of an explanation about how to do, or could orientate me towards useful resources. I would be more than grateful.

Here is the link to the code, if you want to have a glimpse: https://jsixj.csb.app/

EDIT: It's not that the collision is not detected, it is that it is too late: the collision detection triggers late, hence the two rectangles are "deeply tangled", the collision response changes the velocy vectors to the opposite direction, then, next frame, a collision is detected since the two rectangles didn't have time to "detached" from each other, etc. In other words: in each upadate (requestAnimationFrame), the collision is detected and the velocity vectors change accordingly to the opposite direction, but since the rectangles are yet deeply overlapping, they don't have the time to separate.

This issue is well adresses and easy to resolve in the case of circles: Pseudo code:

//We calculate the vector between the center of each circle
 let vect = Vector.sub(Circle1.center, Circle2.center)
//its magnitude
 let dist = Vector.Mag(vect)
//We deduct the unitary vector 
 let unitVect = Vector.div(vect, dist)

//is the two circle are overlapping
 if(dist <= Circle1.radius + Circle2.radius){ 
//we set the new center of Circle1 so that the two circle just touch eachother without overlapping 
    const correction = Vector.mult(unitNormal, Circle1.radius + Circle2.radius)
    const newV = Vector.add(Circle1.pos, correction)
    Circle1.center = newV
}

It is definitely trickier for rectangles, especially when spinning, because I assume, we have to take into account the direction of the rectangle to resolve the problem I'm looking for a clue about the general philosophy for resolving this but if you need to dig a bit in the code I wrote, please refer to the link above

EDIT : to better understand what I was trying to explain above here is another gif to illustrate :

I modelized the velocity vector in green, then you can see what happens when the rectangle gets stuck, the collision detection is too fast changing the velocity direction on each frame therefore avoiding the rectangle to "escape" the edge.

0

There are 0 answers