交集算法

发布于 2024-10-06 04:59:47 字数 144 浏览 1 评论 0原文

我的 CSharp 项目中有两个对象,它们呈现矩形。现在我想计算一个对象是否与另一个对象相交。物体不能旋转。

我有以下方法:

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

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

I've got the following methods:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偏爱自由 2024-10-13 04:59:47

虽然这个问题在技术上与其他问题重复,但我会提出一个比那里发布的更优雅的解决方案。

我会从边界框的角度来看待它。如果边界框比高度之和短且比宽度之和窄,则它们必须相交:

// 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());
}

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());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文