返回介绍

Vector3.sqrMagnitude 长度平方

发布于 2019-12-18 15:38:44 字数 2126 浏览 1376 评论 0 收藏 0

JavaScript => var sqrMagnitude: float;
C# => float sqrMagnitude;

Description 描述

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

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

The magnitude of a vector v is calculated as Mathf.Sqrt(Vector3.Dot(v, v)). However, the Sqrt calculation is quite complicated and takes longer to execute than the normal arithmetic operations. Calculating the squared magnitude instead of using the magnitude property is much faster - the calculation is basically the same only without the slow Sqrt call. If you are using magnitudes simply to compare distances, then you can just as well compare squared magnitudes against the squares of distances since the comparison will give the same result.

一个向量V的长度计算方法是Mathf.Sqrt(Vector3.Dot(v, v))。然而,sqrt计算是相当复杂的,需要更长的时间比正常执行算术操作。计算长度平方来代替直接计算长度速度更快,除掉开根号计算是基本相同的。如果你只是使用大小比较的距离,那么你同样可以比较平方长度大小来比较距离,得到相同的结果。

JavaScript:

	// detects when the other transform is closer than closeDistance
	// this is faster than using Vector3.magnitude	var other : Transform;
	var closeDistance = 5.0;
 
	function Update() {
		if (other) {
			var offset = other.position - transform.position;
			var sqrLen = offset.sqrMagnitude;
			// square the distance we compare with
			if( sqrLen < closeDistance*closeDistance )
				print ("The other transform is close to me!");
		}
	}

C#:

using UnityEngine;
using System.Collections;
 
public class ExampleClass : MonoBehaviour {
    public Transform other;
    public float closeDistance = 5.0F;
    void Update() {
        if (other) {
            Vector3 offset = other.position - transform.position;
            float sqrLen = offset.sqrMagnitude;
            if (sqrLen < closeDistance * closeDistance)
                print("The other transform is close to me!");
 
        }
    }
}

Vector3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文