Unity中常用表示方向的方式
1.欧拉角
transform.eulerAngles
不要单独设置某个 eulerAngles 轴(例如,eulerAngles.x = 10;),这会导致偏差和不希望的旋转。 在将它们设置为新值时,请一次性设置所有 eulerAngles 轴
2.四元数
四元数旋转有个重要的特性就是:到达终止方向的旋转角度为旋转方向
例如起始位置为(0,0,0),绕Y轴旋转200度到(0,200,0),物体会顺时针旋转160度而不是逆时针旋转200度。
(1)四元数的球形插值
static function Slerp (from : Quaternion, to : Quaternion, t : float) : Quaternion
球形插值,通过t值from向to之间插值。可以理解为速度,通常取值为0< t <= 1
public class example : MonoBehaviour
{
public Transform from;
public Transform to;
public float speed = 0.1F;
void Update()
{
//可以把 speed * Time.time 理解成速度 * 时间 等于角位移
transform.rotation = Quaternion.Slerp(from.rotation, to.rotation, Time.time * speed);
}
}
在Unity里,tranform组件有一个变量名为rotation,它的类型就是四元数。
欧拉角和四元数的转换
原理:
public Quaternion EulerToQuaternion(float xx, float yy, float zz)
{
float X = xx / 180 * Mathf.PI;
float Y = yy / 180 * Mathf.PI;
float Z = zz / 180 * Mathf.PI;
float x = Mathf.Cos(Y / 2) * Mathf.Sin(X / 2) * Mathf.Cos(Z / 2) + Mathf.Sin(Y / 2) * Mathf.Cos(X / 2) * Mathf.Sin(Z / 2);
float y = Mathf.Sin(Y / 2) * Mathf.Cos(X / 2) * Mathf.Cos(Z / 2) - Mathf.Cos(Y / 2) * Mathf.Sin(X / 2) * Mathf.Sin(Z / 2);
float z = Mathf.Cos(Y / 2) * Mathf.Cos(X / 2) * Mathf.Sin(Z / 2) - Mathf.Sin(Y / 2) * Mathf.Sin(X / 2) * Mathf.Cos(Z / 2);
float w = Mathf.Cos(Y / 2) * Mathf.Cos(X / 2) * Mathf.Cos(Z / 2) + Mathf.Sin(Y / 2) * Mathf.Sin(X / 2) * Mathf.Sin(Z / 2);
Quaternion quataion = new Quaternion(x, y, z, w);
return quataion;
}
public Vector3 QuaternionToEuler(float xx, float yy, float zz, float ww)
{
float X = Mathf.Asin(2 * (ww * xx - yy * zz));
float Y = Mathf.Atan2(2 * (ww * yy + xx * zz), 1 - 2 * (xx * xx + yy * yy));
float Z = Mathf.Atan2(2 * (ww * zz + yy * xx), 1 - 2 * (xx * xx + zz * zz));
Vector3 euler = new Vector3(X * 180f / Mathf.PI, Y * 180f / Mathf.PI, Z * 180f / Mathf.PI);
return euler;
}
方法:
//EulerToQuaternion
Quaternion.Euler(transform.eulerAngles),
//QuaternionToEuler
q.eulerAngles