Unity十一 向量

2021-09-14 08:37:06 字數 2828 閱讀 4157

這裡不多介紹關於向量的加減乘除的原理,只是介紹 unity3d裡關於向量的給好的方法和屬性,利用這些方法和屬性我們就可以得到向量加減 叉乘點乘 除法的計算。

1、獲得向量的大小,在 unity 中給出了兩個方法。

vector3 a = new vector3(3, 4, 5);

float b = vector3.magnitude(a);

float c = a.magnitude;

print("獲取長度的兩種方法:" + b + "::::" + c);

2、distance vector3的方法,返回float 型,得到兩個向量之間的距離。

vector3 a = new vector3(3, 4, 5);

vector3 b = new vector3(5, 6, 7);

float c = vector3.distance(a, b);

print(c);

3、向量的加法減法,當然得到的依然是個 vector3向量。

vector3 v1 = new vector3(2, 3, 4);

vector3 v2 = new vector3(3, 4, 9);

vector3 v3 = v1 + v2;

vector3 v4 = v1 - v2;

print("加法" + v3);

print("減法" + v4);

4、向量乘以除以數字

vector3 v5 = v1 * 0.1f;

print("乘以數字" + v5);

vector3 v6 = v2 / 10;

print("除以數字" + v6);

5、向量歸一化(向量轉為單位向量(方向不變,長度變為1)),unity 給出了屬性normalized和方法 normalize

相同和區別:

vector3 a = new vector3(3, 4, 8);

vector3 b = a.normalized;

print(b);

print(b.magnitude);

vector3 c = new vector3(5, 7, 9);

vector3 d = vector3.normalize(c);

print(c);

print(d);

vector3 e = new vector3(8, 9, 5);

e.normalize();

print(e);

6、向量的叉乘cross,vector3的方法,返回的是 vector3向量。而在實際數學中叉乘得到的是乙個數字,|c|=|a||b|sin,那麼這裡我們還可以在利用unity 給出的屬性a.normalized獲得叉乘的模長。

//兩個向量叉乘

vector3 a = new vector3(3, 5, 7);

vector3 b = new vector3(5, 8, 2);

vector3 c = vector3.cross(a, b);

print(c.magnitude);

float angle1 = mathf.asin(vector3.cross(a.normalized, b.normalized).magnitude) * mathf.rad2deg;

float angle2 = mathf.asin(vector3.distance(vector3.zero, vector3.cross(a.normalized, b.normalized))) * mathf.rad2deg;

print(angle1);

print(angle2);

7、點乘。|c|=|a||b|cos。返回 float 型。

vector3 a = new vector3(8, 9, 10);

vector3 b = new vector3(2, 4, 6);

float c = vector3.dot(a, b);

print(c);

float angle = mathf.acos(vector3.dot(a.normalized, b.normalized)) * mathf.rad2deg;

print(angle);

8、lerp方法。返回從 a 點到 b 點的中間的某個點。應用在平緩移動以及相機跟隨。

i、列印vector3.lerp的值

vector3 a = new vector3(3, 4, 5);

vector3 b = new vector3(6, 7, 8);

vector3 c = vector3.lerp(a, b, 0);

print("0:::返回的是 a" + c);

vector3 d = vector3.lerp(a, b, 1);

print("1::: 放回的 b" + d);

vector3 e = vector3.lerp(a, b, 0.5f);

print("0.5::::返回的是a、b 中間的位置" + e);

ii、在場景中移動,cube 向 shpere 移動

gameobject cube;

gameobject sphere;

// use this for initialization

void start ()

// update is called once per frame

void update ()

Unity向量學習的隨筆

如果空間中的一點與另一點相減,則得到乙個從乙個物體 指向 另乙個物體的向量 gets a vector that points from the player s position to the target s.var heading target.position player.position...

學習雜記十一 棧和向量

用兩個棧來實現乙個佇列,完成佇列的push和pop操作。佇列中的元素為int型別。class solution stack1.push node int pop int s stack2.top stack2.pop return s private stackstack1 stackstack2 ...

Unity 初識 座標系與向量

世界座標系 場景中的絕對座標系,場景上所有物體都是以該座標系的原點來確定各自位置的。世界座標即物體在世界座標系中的位置。區域性座標系 以物體的世界座標為原點,角度為朝向,大小為單位,所產生乙個新的座標系,該座標系中,物體的位置 旋轉 大小都會受到此座標系的影響。區域性座標即物體在區域性座標系中的位置...