向量的概念高中有学习过,这里指的就是Vector,即有方向的量。
Vector2: sqrt(x²+y²)
Vector3: sqrt(x²+y²+z²)
用API求长度:
-------------------------------------------------------------------------
Vector2 vector = new Vector2(2, 2);
float n = vector.magnitude;
-------------------------------------------------------------------------
把向量的长度缩放成1,方向不变,即单位向量。
(3,4)->(0.6,0.8)
(0,2)->(0,1)
用API进行标准化:
-------------------------------------------------------------------------
Vector3 a = new Vector3(3f, 4f, 0);
Vector3 b = a.normalized; //将向量a标准化
Debug.Log("a的标准化:" + b.ToString("F3"));//F3:保留三位小数
-------------------------------------------------------------------------
输出:
a的标准化:(0.600, 0.800, 0.000)
若不指定参数F3,直接输出b,也能输出,但是只会保留一位小数:
-------------------------------------------------------------------------
Vector3 a = new Vector3(2f, 2f, 0);
Vector3 b = a.normalized; //将向量a标准化
Debug.Log("a的标准化:" + b);//F3:保留三位小数
-------------------------------------------------------------------------
输出:
a的标准化:(0.7, 0.7, 0.0)
Vector3.right:(1,0,0)
Vector3.up:(0,1,0)
Vector3.forward:(0,0,1)
Vector3 a = new Vector3(3, 1, 0);
Vector3 b = new Vector3(1, 2, 0);
Vector3 c = a + b;
Debug.Log("c:" + c);
输出:
c: (4.0, 3.0, 0.0)
Vector3 a = new Vector3(3, 3, 0);
Vector3 b = new Vector3(1, 2, 0);
Vector3 c = a - b;
Debug.Log("c:" + c);
输出:
c: (2.0, 1.0, 0.0)
Vector3 a = new Vector3(3f, 3f, 0);
Vector3 b = new Vector3(1f, 2f, 0);
Vector3 c1 = a * 2;
Debug.Log("标量乘法: " + c1);
float c2 = Vector3.Dot(a, b);
Debug.Log("点积: " + c2); //数量积
Vector3 c3 = Vector3.Cross(a, b);
Debug.Log("叉积: " + c3); //向量积
输出:
标量乘法: (6.0, 6.0, 0.0)
点积: 9 //a·b=|a||b|·cosθ
叉积: (0.0, 0.0, 3.0) //|c|=|a||b|·sinθ
通过向量的减法求物体间的距离是很常见的。
GameObject bullet = GameObject.Find("bullet");
Vector3 p1 = bullet.transform.position;
Vector3 p2 = this.transform.position;
Vector3 direction = p2 - p1;
Debug.Log("物体间的距离:" + direction.magnitude);
--------------------------------------------
a:起始向量
b:终点向量
Vector3:旋转轴
Angle:无符号的角度
SignedAngle:带符号的角度
返回:从a->的角度,逆时针为正,顺时针为负
--------------------------------------------
Vector3.Angle(a, b, Vector3);
Vector3.SignedAngle(a, b, Vector3);
void Start()
{
Vector3 a = new Vector3(1, 0, 0);
Vector3 b = new Vector3(0, 1, 0);
float angle = Vector3.SignedAngle(a, b, Vector3.forward);
Debug.Log("a与b的夹角:" + angle);
}
输出:
a与b的夹角:90
void Start()
{
Vector3 a = new Vector3(1, 0, 0);
Vector3 b = new Vector3(0, 1, 0);
float angle = Vector3.SignedAngle(b, a, Vector3.forward);
Debug.Log("a与b的夹角:" + angle);
}
输出:
a与b的夹角:-90
当两向量方向相反时,结果必为180
X轴的指向:transform.right
Y轴的指向:transform.up
Z轴的指向:transform.forward
这三个向量都是标准向量(长度为1),用于表示物体的坐标系
Vector3 face = this.transform.up;
GameObject target = GameObject.Find("物体");
Vector3 direction = target.transform.position - this.transform.position;//对象指向物体的方向
float angle = Vector3.SignedAngle(face, direction, Vector3.forward)//计算旋转的角度
this.transform.Rotate(0, 0, angle);