开发者

Intersection algorithm

开发者 https://www.devze.com 2023-01-29 01:32 出处:网络
I have two objects in a CSharp project, which presents rectangles. Now I want to calculate if one object 开发者_C百科intersects another one. The objects cannot rotate.

I have two objects in a CSharp project, which presents rectangles. Now I want to calculate if one object 开发者_C百科intersects another one. The objects cannot rotate.

I've got the following methods:

getX();
getY();
getWidth();
getHeight();


While this is technically a duplicate of that other question, I would propose a more elegant solution than what was posted there.

The way I would look at it would be from the perspective of the bounding box. If the bounding box is shorter than the sum of the heights AND skinnier than the sum of the widths, they must intersect:

// assume we have a class with a constructor like so...
class Rect
{
    ...
    void Rect(int top, int left, int bottom, int right) { ... }
    ...
}

...

private Rect GetBoundingRect(Rect r1, Rect r2)
{
    int left = min(r1.getX(), r2.getX());
    int right = max(r1.getX()+r1.getWidth(), r2.getX()+r2.getWidth());
    int top = min(r1.getY(), r2.getY());
    int bottom = max(r1.getY()+r1.getHeight(), r2.getY()+r2.getHeight());
    return new Rect( top, left, bottom, right );
}

private bool CheckIfIntersect(Rect r1, Rect r2)
{
    Rect bound = GetBoundingRect(r1,r2);
    return (bound.getWidth() < r1.getWidth() + r2.getWidth()) &&
           (bound.getHeight() < r1.getHeight() + r2.getHeight());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号