Vector3.sqrMagnitude 长度平方

var sqrMagnitude : float

Description描述

Returns the squared length of this vector (Read Only).

返回这个向量的长度的平方(只读)。

Calculating the squared magnitude instead of the magnitude is much faster. Often if you are comparing magnitudes of two vectors you can just compare their squared magnitudes.

计算长度的平方而不是magnitude是非常快的。如果你是比较两个向量的长度差,你可以比较他们的平方长度。

向量的长度是用勾股定理计算出来,计算机计算两次方和开根的运算量比加减法要费时的多。所以如果是想比较两个向量的长度,用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!");

		}
	}
}
// detects when the other transform is closer than closeDistance
// this is faster than using Vector3.magnitude
//当其他变换比closeDistance更近时检测
//这比使用Vector3.magnitude更快
var other : Transform;
var closeDistance = 5.0;

function Update() {
	if (other) {
		var sqrLen = (other.position - transform.position).sqrMagnitude;
		// square the distance we compare with
		//我们比较距离的平方
		if( sqrLen < closeDistance*closeDistance )
			print ("The other transform is close to me!");
	}
}

参见: magnitude.

最后修改:2010年12月19日 Sunday 21:27

本脚本参考基于Unity 3.4.1f5

英文部分版权属©Unity公司所有,中文部分© Unity圣典 版权所有,未经许可,严禁转载 。