首先要知道一点就是在Unity的旋转中使用过四元数进行旋转的,如果对一个物体的rotation直接赋值你会发现结果不是你最终想要的结果,这个时候我们需要去借助Quaternion来进行旋转。
用到的Unity内置方法Quaternion.AngleAxis(float angle,Vector3 axis)
第一个参数就是我们需要旋转的角度 angle大于0时是按照顺时针的方向进行旋转,angle小于0是按照逆时针的方向旋转,这里的旋转时按照坐标原点进行的旋转。
第二个参数是旋转轴,围绕哪一个坐标轴进行旋转。
using UnityEngine;
[ExecuteInEditMode]
public class VectorDirTest : MonoBehaviour {
// Update is called once per frame
void Update () {
Debug.DrawLine(Vector3.left * 5f,Vector3.right * 5f,Color.red);
Debug.DrawLine(Vector3.up * 5f,Vector3.down * 5f,Color.green);
Debug.DrawLine(Vector3.forward * 5f,Vector3.back * 5f,Color.blue);
Vector3 dir = new Vector3(1,0,1);
Debug.DrawLine(Vector3.zero,dir,Color.white);
Debug.DrawLine(Vector3.zero,Quaternion.AngleAxis(45,Vector3.up) * dir,Color.black);
Debug.DrawLine(Vector3.zero,Quaternion.AngleAxis(90,Vector3.up) * dir,Color.yellow);
Debug.DrawLine(Vector3.zero,Quaternion.AngleAxis(180,Vector3.up) * dir,Color.blue);
Debug.DrawLine(Vector3.zero,Quaternion.AngleAxis(270,Vector3.up) * dir,Color.green);
}
}
///
/// 围绕某点旋转指定角度
///
/// 自身坐标
/// 旋转中心
/// 围绕旋转轴
/// 旋转角度
///
public Vector3 RotateRound(Vector3 position, Vector3 center, Vector3 axis, float angle)
{
return Quaternion.AngleAxis(angle, axis) * (position - center) + center;
}
代码如下:
using UnityEngine;
[ExecuteInEditMode]
public class VectorDirTest : MonoBehaviour {
// Update is called once per frame
void Update () {
Debug.DrawLine(Vector3.left * 5f,Vector3.right * 5f,Color.red);
Debug.DrawLine(Vector3.up * 5f,Vector3.down * 5f,Color.green);
Debug.DrawLine(Vector3.forward * 5f,Vector3.back * 5f,Color.blue);
Vector3 dir = new Vector3(1,0,1);
Vector3 point = new Vector3(2,0,2);
Debug.DrawLine(Vector3.zero, RotateRound(dir, point, Vector3.up, 45), Color.red);
Debug.DrawLine(Vector3.zero, RotateRound(dir, point, Vector3.up, 90), Color.yellow);
Debug.DrawLine(Vector3.zero, RotateRound(dir, point, Vector3.up, 180), Color.blue);
Debug.DrawLine(Vector3.zero, RotateRound(dir, point, Vector3.up, 270), Color.green);
Debug.DrawLine(Vector3.zero, dir, Color.black);
}
///
/// 围绕某点旋转指定角度
///
/// 自身坐标
/// 旋转中心
/// 围绕旋转轴
/// 旋转角度
///
public Vector3 RotateRound(Vector3 position, Vector3 center, Vector3 axis, float angle)
{
return Quaternion.AngleAxis(angle, axis) * (position - center) + center;
}
}