求两条直线的交点量
使用如下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个答案很明显,我也明白了。
只需从 outVect 的 X 和 Y 中减去 a1 和 a2:
这会否定其位置。
This answer was pretty obvious, and I figured it out.
Just subtract a1 and a2 from X and Y of outVect:
This negates its location.