我有一个 XNA 问题要问那些在这些问题上比我更有经验的人(数学)。
背景:我有一个实现边界类的游戏,它仅托管 2 个 Vector2 对象、一个起点和一个终点。当前的实现通过假设边界始终是垂直或水平来粗略地处理碰撞检测,即如果 start.x 和 end.x 是相同的检查,我不会尝试通过 x 等。
理想情况下,我想要实现的是一个接受两个 Vector2 参数的方法。第一个是当前位置,第二个是请求的位置(假设没有异议,我想将其移动到该位置)。该方法还接受一个边界对象。然后该方法应该做的是告诉我在这一步中我是否要跨越边界。这可能是一个 bool 值,或者理想情况下代表我实际可以移动多远的东西。
这个空方法可能比我用语言更好地解释。
/// <summary>
/// Checks the move.
/// </summary>
/// <param name="current">The current.</param>
/// <param name="requested">The requested.</param>
/// <param name="boundry">The boundry.</param>
/// <returns></returns>
public bool CheckMove(Vector2 current, Vector2 requested, Boundry boundry)
{
//return a bool that indicated if the suggested move will cross the boundry.
return true;
}
最佳答案
经过相当多的研究,最重要的是找到了谷歌的正确术语,我有了一个解决方案,我刚刚将其内置到我的测试台中,并且它运行得很好。
我拿了网上找到的一个例子进行了测试,然后修改了一下,以满足本题的需要。应该指出的是,自测试以来我已经进行了更改,因为我在这台笔记本电脑上只有一个虚拟机,无法运行 XNA 应用程序,因此虽然我确信它应该可以工作,但可能会出现错误。
我们需要做的就是传入一个表示我们所在位置的向量、一个表示我们想要的位置的向量以及边界(实际上是由起始向量和结束向量组成的线)。该方法将告诉我们两条线(一条是当前位置和请求位置之间的路径,另一条是边界)是否交叉。作为额外的好处,如果他们进行交叉,输出参数会告诉我们在哪里。
这是一个非常有用的系统,可用于创建强大的碰撞检测。
/// <summary>
/// Based on the 2d line intersection method from "comp.graphics.algorithms Frequently Asked Questions"
/// </summary>
/// <param name="currentLocation">The current location.</param>
/// <param name="requestedLocation">The requested location.</param>
/// <param name="boundary">The boundary.</param>
/// <param name="collisionVector">The collision vector.</param>
/// <returns></returns>
public static bool Intersects(Vector2 currentLocation, Vector2 requestedLocation, Boundary boundary, ref Vector2 collisionVector)
{
float q = (currentLocation.Y - boundary.Start.Y) * (boundary.End.X - boundary.Start.X) - (currentLocation.X - boundary.Start.X) * (boundary.End.Y - boundary.Start.Y);
float d = (requestedLocation.X - currentLocation.X) * (boundary.End.Y - boundary.Start.Y) - (requestedLocation.Y - currentLocation.Y) * (boundary.End.X - boundary.Start.X);
if (d == 0)
{
return false;
}
float r = q / d;
q = (currentLocation.Y - boundary.Start.Y) * (requestedLocation.X - currentLocation.X) - (currentLocation.X - boundary.Start.X) * (requestedLocation.Y - currentLocation.Y);
float s = q / d;
if (r < 0 || r > 1 || s < 0 || s > 1)
{
return false;
}
collisionVector.X = currentLocation.X + (int)(0.5f + r * (requestedLocation.X - currentLocation.X));
collisionVector.Y = currentLocation.Y + (int)(0.5f + r * (requestedLocation.Y - currentLocation.Y));
return true;
}
关于c# - XNA、C# - 检查 Vector2 路径是否与另一个 Vector2 路径交叉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4504125/