,所以我有一个对象和一个目标。它们都有随时间变化的X和Z位置。
我跟踪当前位置和以前的位置。职位可以是正面的或负的。
我目前正在尝试找出一种方法来确定对象是否正在向指定目标移动。
这是我正在从事的代码
if ((Math.Abs(this.previousPosition.X) - Math.Abs(this.currentPosition.X)) > Math.Abs(target.currentPosition.X)
&& (Math.Abs(this.previousPosition.Z) - Math.Abs(this.currentPosition.Z)) > Math.Abs(target.currentPosition.Z))
{
//is moving to target
return true;
}
//is not moving to target
return false;
我的建议是比较'this'与目标之间的距离,如下:
private bool IsApproachingTarget(double epsilon)
{
float prevDist, currDist;
Vector3.DistanceSquared(ref this.previousPosition, ref target.previousPosition, out prevDist);
Vector3.DistanceSquared(ref this.currentPosition, ref target.currentPosition, out currDist);
return IsLess(currDist, prevDist, epsilon);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
/// <summary>
/// Robust implementation of a < b, handling floating point imprecisions
/// </summary>
public bool IsLess(double a, double b, double epsilon)
{
return a < b - epsilon;
}
请注意,我使用vector3.distancesquared而不是vector3.distance。这是一个普遍的性能技巧,如果您只想比较向量的大小,并且您对跳过不必要的正方根计算的实际幅度不感兴趣。
您可以将结果存储在每个游戏循环中,因为这样进行了两次距离计算...
和vector3.distancesquared措施欧几里得距离,也许简单的曼哈顿距离也会为您带来。
Methodimpl属性只是.NET 4.5中引入的额外优化功能。如果您较早针对.NET框架版本,则可以跳过它。