向量的长度是用勾股定理计算出来,计算机计算两次方和开根的运算量比加减法要费时的多。所以如果是想比较两个向量的长度,用sqrMagnitude可以快出很多。
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
public Transform other;
public float closeDistance = 5.0F;
void Update() {
if (typeof(other)) {
float sqrLen = other.position - transform.position.sqrMagnitude;
if (sqrLen < closeDistance * closeDistance)
print("The other transform is close to me!");
}
}
}