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.

Page last updated: 2010-12-19