求两条直线的交点量

发布于 2024-11-06 06:05:32 字数 907 浏览 1 评论 0原文

使用如下代码:

    static bool Intersects(Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2, out Vector2 intersection)
    {
        intersection = Vector2.Zero;

        Vector2 b = a2 - a1;
        Vector2 d = b2 - b1;
        float bDotDPerp = b.X * d.Y - b.Y * d.X;


        if (bDotDPerp == 0)
            return false;

        Vector2 c = b1 - a1;
        float t = (c.X * d.Y - c.Y * d.X) / bDotDPerp;
        if (t < 0 || t > 1)
            return false;

        float u = (c.X * b.Y - c.Y * b.X) / bDotDPerp;
        if (u < 0 || u > 1)
            return false;

        intersection = a1 + t * b;

        return true;
    }

我可以确定两条线碰撞的位置。但是,坐标是相对于窗口给出的,而不是彼此之间的。例如,假设两条线彼此垂直。其中一个与第二个在 0,0 处一像素重叠。这意味着要解决此碰撞,我需要向后移动 1 个像素。但是,如果我在 400,400 处执行相同的测试,它会告诉我它在 399, 399 处相交。显然我不必在 399, 399 处解决碰撞。

我希望使用此信息来找出答案线条重叠了多少,以便我可以将它们适当地移回原处。我必须做什么才能做到这一点?

Using a bit of code like this:

    static bool Intersects(Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2, out Vector2 intersection)
    {
        intersection = Vector2.Zero;

        Vector2 b = a2 - a1;
        Vector2 d = b2 - b1;
        float bDotDPerp = b.X * d.Y - b.Y * d.X;


        if (bDotDPerp == 0)
            return false;

        Vector2 c = b1 - a1;
        float t = (c.X * d.Y - c.Y * d.X) / bDotDPerp;
        if (t < 0 || t > 1)
            return false;

        float u = (c.X * b.Y - c.Y * b.X) / bDotDPerp;
        if (u < 0 || u > 1)
            return false;

        intersection = a1 + t * b;

        return true;
    }

I can determine where two lines collide. However, the coordinates are given relative to the window, not each other. For example, say the two lines are perpendicular to one another. One of them overlaps the second one by one pixel at 0,0. This would mean that to resolve this collision, I would need to move back 1 pixel. However, if I performed this same test at say, 400,400, it would tell me that it intersects at 399, 399. I obviously do not have to resolve the collision by 399, 399.

I'm looking to use this information to find out how much the lines are overlapping so I can move them back appropriately. What must I do to do this?

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

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

发布评论

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

评论(1

把昨日还给我 2024-11-13 06:05:32

这个答案很明显,我也明白了。

只需从 outVect 的 X 和 Y 中减去 a1 和 a2:

(outVect.X-a1.X), (outVect.Y-a1.Y)

这会否定其位置。

This answer was pretty obvious, and I figured it out.

Just subtract a1 and a2 from X and Y of outVect:

(outVect.X-a1.X), (outVect.Y-a1.Y)

This negates its location.

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