简体   繁体   中英

How to handle the 4 sides of rect object in case of intersectsWith another one?

I have to 2 rect objects. One of that cannot move, another one is moving. I would like handle that when its intersectsWith the first one of each side. Something like:

if (rect1.IntersectsWith(rect2))
 {
     if (rect1.Top == rect2.Bottom)
     {
      ...
     }
     else if (rect1.Bottom == rect2.Top)
     {
      ...
     }
     else if (rect1.Left == rect2.Right)
     {
      ...
     }
     else if (rect1.Right == rect2.Left)
     {
      ...
     }
 }

This gives me not an accurate results. Any idea?

It appears that you already have a way to determine whether the two rectangles are colliding, which is good because it makes your job easier. All you have to do now is to determine which side the collision happened on, and then to act accordingly.

If that's the case, then you're already on the right track. However, your logic on the checks is a bit faulty. You're checking if one edge is exactly on top of another edge. In most applications, this is actually pretty rare. What you should be checking is if there is any overlap, which you need the <= and >= comparators for.

if (rect1.IntersectsWith(rect2))
{
    // assumes that positive Y signifies downward direction
    if (rect1.Top <= rect2.Bottom)
    {
        ...
    }
    else if (rect1.Bottom >= rect2.Top)
    {
        ...
    }
    else if (rect1.Left <= rect2.Right)
    {
        ...
    }
    else if (rect1.Right >= rect2.Left)
    {
        ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM