Get the points of intersection from 2 rectangles

后端 未结 5 1930
余生分开走
余生分开走 2020-12-13 05:06

Let say that we have two rectangles, defined with their bottom-left and top-right corners. For example: rect1 (x1, y1)(x2, y2) and rect2 (x3, y3)(x

5条回答
  •  心在旅途
    2020-12-13 05:35

    Let's say that a box has a radius X and radius Y (I know it has not but this term is useful here).

    You will have:

    rect1_x_radius = (x2-x1)/2
    rect1_y_radius = (y2-y1)/2
    

    and

    rect2_x_radius = (x4-x3)/2
    rect2_y_radius = (y4-y3)/2
    

    Now if rect middle points are further away than sum of their radiuses in appropriate direction - they do not collide. Otherwise they do - this hint should suffice.

    You should be now able to finish your assignment.

    UPDATE:

    OK - let's solve it for 1D - later you'll solve it for 2D. Look at this piece of ... art ;-)

    enter image description here

    You see 2 segments - now some calculations:

    rA = (maxA-minA) / 2
    rB = (maxB-minB) / 2
    
    midA = minA + rA
    midB = minB + rB
    
    mid_dist = |midA - midB|
    

    Now how to check if collision occurs? As I said if sum of 'radiuses' is less than segments' distance - there is no collision:

    if ( mid_dist > fabs(rA+rB) )
    {
        // no intersection
    }
    else
    {
        // segments intersect
    }
    

    Now it is your work to calculate intersection / common part in 1D and 2D. It is up to you now (o ryou can read Andrey's answer).

    Here is the same situation but in 2D - two 1D situations:

    enter image description here

提交回复
热议问题