EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

DE

[Unity3D]向量Vector3

在Unity中,用结构体来描述向量,什么是结构体请看→这里

namespace UnityEngine
{
    public struct Vector3
    { 
        public float x;
        public float y;
        public float z;
     }
}

向量的长度:向量的大小(或长度)称为向量的模

[图片]

Mathf.Sqrt()用来返回平方根

public float magnitude
{
    get
    {
        return Mathf.Sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
    }
}

magnitude (Read Only)返回向量的长度,也就是点P(x,y,z)到原点(0,0,0)的距离。 

public float sqrMagnitude
{
    get
    {
        return this.x * this.x + this.y * this.y + this.z * this.z;
    }
}

sqrMagnitude (Read Only)返回未开方的数据。

 

Q:为什么要存在sqrMagnitude?

A:因为比较magnitude的大小,不如比较sqrMagnitude,这样省去了开方操作,减少资源开销。

 


三维空间中两点的距离:

public static float Distance(Vector3 a, Vector3 b)
{
    Vector3 vector = new Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
    return Mathf.Sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z);
}

这些都是帮你写好了的方法。

 


源定义操作符+-

 

向量+

public static Vector3 operator +(Vector3 a, Vector3 b)
{
    return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
}

向量-

public static Vector3 operator -(Vector3 a, Vector3 b)
{
    return new Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
}

 

参考文档:

[1] Vector3向量

This article was last edited at 2020-03-30 21:07:30

* *