Vector3.magnitude和vector3.normalized解释

Ale*_*tic 3 c# unity-game-engine

我正在看这个代码,不知道这是什么magnitude,normalized做什么以及这个人如何使用它们.在文档中只有很少的东西,但它没有解释太多.

我正在看的代码是:

public float minDistance = 1.0f;
public float maxDistance = 4.0f;
public float smooth = 10.0f;
Vector3 dollyDir;
public Vector3 dollyDirAdjusted;
public float distance;

void Awake()
{
    dollyDir = transform.localPosition.normalized;
    //What has he got with this? Documentation says Returns this vector with
    //a magnitude of 1 so if i get it it return's it's length as 1. So what is the point?

    distance = transform.localPosition.magnitude;
    //Have no idea what he got with this
}
void Update()
{
    Vector3 desiredPos = transform.parent.TransformPoint(dollyDir * maxDistance);
    //I know what TransfromPoint does but what is he getting with this dollyDir * maxDistance

    //Some other code which i understand
}
Run Code Online (Sandbox Code Playgroud)

如果有人能解释我,我就在这里 Mathf.Clamp

文档clamp是如此不清楚我如何得到它是我给出顶部和底部值1 and 5,如果我设置value = 3它将返回3,但如果我设置值> 5它将返回5,如果我设置值<1它将返回1?

谢谢.

zam*_*ari 5

Vector3.magnitude返回一个浮点数,它是一个表示向量长度的单维值(因此它会丢失方向信息)

Vector3.normalized是一个相反的操作 - 它返回向量方向,保证结果向量的幅度为1(它保留方向信息但丢失幅度信息).

当你想要分离这两种看向量的方式时,这两者通常是有用的,例如,如果你需要在两个物体之间产生影响,其中影响与它们之间的距离成反比,你可以做

float mag=(targetpos-mypos).magnitude;
if (mag<maxRange)
{
Vector3 dir=(targetpos-mypos).normalized;
Vector3 newVector=dir*(maxRange-mag);
}
Run Code Online (Sandbox Code Playgroud)

这是我最常见的用例,我不确定原始代码的作者是什么意思,因为它似乎可以使用向量差异而不使用两个额外的调用

Mathf.Clamp返回值的值位于min和max之间,如果lower更低则返回min,max if更大.

Vector3的另一个有趣特性是sqrMagnitude,它返回^ 2 + b ^ 2 + c ^ c而不计算平方根.虽然它增加了代码的复杂性(你需要将它与平方距离进行比较),但它节省了相对昂贵的根计算; 略微优化但稍微难以阅读的版本看起来像这样

Vectior3 delta=targetpos-mypos;
if (delta.sqrMagnitude<maxRange*maxRange)
 {
  Vector3 dir=delta.normalized;
  Vector3 newVector=dir*(maxRange-delta.magnitude);
}
Run Code Online (Sandbox Code Playgroud)