CPU比较擅长浮点数相乘,但不擅长计算它们的平方根。magnitude属性,Distance()方法,会执行平方根计算,会消耗大量的CPU开销。sqrMagnitude属性,距离的平方,但不需要昂贵平方根计算。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* Author:W
* 距离的平方
*/
public class SqrMagnitudeTest : MonoBehaviour {
public float targetDistance = 100;
public Transform other;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
/// <summary>
/// 一般计算距离的方式1
/// </summary>
private void Compute1()
{
float distance = (transform.position - other.position).magnitude;
if (distance < targetDistance)
{
//Not Do
}
}
/// <summary>
/// 一般计算距离方式2
/// </summary>
private void Compute2()
{
float distance = Vector3.Distance(transform.position,other.position);
if (distance < targetDistance)
{
//Not DO
}
}
/// <summary>
/// 性能比较好的计算距离的方式:距离的平方
/// </summary>
private void Compute3()
{
float sqrDistance = (transform.position - other.position).sqrMagnitude;
if (sqrDistance < targetDistance * targetDistance)
{
//Not Do
}
}
}
总结:在不需要非常精确的计算模式时,可以使用距离的平方来代替计算判断检查。