Search code examples
geometrycollisionrectangles

How to get penetration vector of two rects?


Suppose if I have two rects with x,y,w,h and one is stationary and the other is moving at vx, vy. I already calculated that they overlap each other and I know the overlap rect as well. What I am interested in finding out is the red vector in the below graph:

enter image description here

This is different than a minimum adjustment vector because as you can see, the minimum adjustment would just move rect A leftwards, whereas the red vector moves it leftwards and upwards. Is there an efficient way to calculate this?


Solution

  • The movement vector V0 and penetration vector V1 are anti-parallel

    so you can exploit that: img where dx,dy is the overlap area size so

    if (|V0.x|>=|V0.y|)
     {
     V1.x=-sign(V0.x)*|dx|
     V1.y=-sign(V0.y)*|dx*V0.y/V0.x|
     }
    
    if (|V0.x|<|V0.y|)
     {
     V1.y=-sign(V0.y)*|dy|
     V1.x=-sign(V0.x)*|dy*V0.x/V0.y|
     }
    

    Hope I did not make some silly mistake but anyway the idea behind should be strait-forward. If not make the parametric line equation of V0 ... You can also exploit the dot product for this but that should lead to the same results ...