两种方法:
- 向量的模长
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没有开方操作,实际应用中效率会更好。
- 向量的Distance方法
Vector3 position1 = Vector3.zero;
Vector3 position2 = Vector3.one;
// 结果 distance = 1.73205278
float distance = Vector3.Distance(position1, position2);
进阶理解
- √(x^2 + y^2 + z^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);
}
- 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);
}
- 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);
}