向量
Contents
- 向量可以代表位置 也可以代表方向
- 三维向量Vector3
- 二维向量Vector2
两个点决定一个向量
Vector3 A = new Vector3(1, 2, 3);
Vector3 B = new Vector3(5, 1, 5);
//B相对于A的向量
Vector3 AB = B - A;
//A相对于B的向量
Vector3 BA = A - B;向量的模长
两个点之间的长度
Vector3 C = new Vector3(5, 6, 7);
//原点到C的长度
print(C.magnitude);
//等于Vector3.Distance(Vector.zero,c);单位向量
//Vector3中提供了获取单位向量的成员属性
AB.normalized
//等同于AB / AB.magnitude向量点乘
- 可通过点乘计算出|A|的值
- 点乘的计算公式
- 向量A(Xa,Ya,Za)
- 向量B(Xb,Yb,Zb)
- AB = Xa*Xb+Ya*Yb+Za*Zb
- 点乘结果>0 两个向量的夹角为锐角
- 点乘结果=0 两个向量夹角为直角
- 点乘结果<0 两个向量夹角为钝角
float dotResult = Vector3.Dot(B.transform.position, target.position - this.transform.position);通过点乘推导出夹角
使用单位向量计算点乘
//得到|A| 因为使用单位向量斜边OA等于1 临边是叉乘结果 cosβ = 角的临边/斜边
float dotResult = Vector3.Dot(B.transform.forward, (target.position - this.transform.position).normalized);
//使用叉乘结果 通过反向三角函数得到角度
Mathf.Acos(dotResult)使用API直接得到夹角
Vector3.Angle(this.transform.forward, target.position - this.transform.position);叉乘
- 可以通过叉乘来计算物体在左边还是右边
- 叉乘的计算
- 向量A(Xa,Ya,Za)
- 向量B(Xb,Yb,Zb)
- A×B = (x,y,z)
- x = Ya*Zb - Za*Yb
- y = Za*Xb - Xa*Zb
- z = Xa*Yb - Ya * Zb
//假设向量 A和B 都在 XZ平面上
//向量A 叉乘 向量 B
//y大于0 证明 B在A右侧
//y小于0 证明 B在A左侧
Vector3 C = Vector3.Cross(B.position, A.position);