Unity3D两点之间距离的计算

两种方法:

  1. 向量的模长
Vector3 position1 = Vector3.zero;
Vector3 position2 = Vector3.one;
// magnitude = 向量的模长 
// 结果 distance = 1.73205078
float distance = (position1 - position2).magnitude;
// sqrMagnitude = 向量模长的平方
// 结果 sqlDistance = 3
float sqlDistance = (position1 - position2).sqrMagnitude;
  • 注意:sqrMagnitude没有开方操作,实际应用中效率会更好。
  1. 向量的Distance方法
Vector3 position1 = Vector3.zero;
Vector3 position2 = Vector3.one;
// 结果 distance = 1.73205278
float distance = Vector3.Distance(position1, position2);

进阶理解

  1. √(x^2 + y^2 + z^2) 三个轴差值的平方和,然后开根号。
  2. magnitude计算方法
public float magnitude
{
    [MethodImpl((MethodImplOptions) 256)] get => (float) Math.Sqrt((double) this.x * (double) this.x + (double) this.y * (double) this.y + (double) this.z * (double) this.z);
}
  1. sqrMagnitude计算方法
public float sqrMagnitude
{
    [MethodImpl((MethodImplOptions) 256)] get => (float) ((double) this.x * (double) this.x + (double) this.y * (double) this.y + (double) this.z * (double) this.z);
}
  1. Distance函数方法
[MethodImpl((MethodImplOptions) 256)]
public static float Distance(Vector3 a, Vector3 b)
{
    float num1 = a.x - b.x;
    float num2 = a.y - b.y;
    float num3 = a.z - b.z;
    return (float) Math.Sqrt((double) num1 * (double) num1 + (double) num2 * (double) num2 + (double) num3 * (double) num3);
}
posted @ 2023-09-22 11:18  EzHappy  阅读(1187)  评论(0)    收藏  举报