四元数x向量,相关用法

Vector3 operator *(Quaterion rotation, Vector3 point)

点绕着原点旋转指定的角度。不管如何旋转这个点都是在一个圆球的表面上(圆球半径为point到原点的距离)。

 

几个例子

测试代码

public class QuatTest : MonoBehaviour
{
    public Vector3 m_QuatEuler;
    private Vector3 m_Point;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            var point = new Vector3(0, 0, -1);
            m_Point = Quaternion.Euler(m_QuatEuler) * point;
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.cyan;
        Gizmos.DrawLine(Vector3.zero, m_Point);
    }

}

1) x轴旋转45度

 

2) x, y轴都旋转45度

 

3) x, y, z都旋转45度,貌似和2)没有区别,主要是point本身就在z轴上,绕z轴旋转没任何效果的

 

一些疑问

有时候,我们会看到this.transform.rotation * point直接这样用,如果用this.transform.localRotation * point有区别吗?

1) 有区别,比如localRotation是x轴30度,rotation却是无任何旋转(parent反方向旋转了),这种情况就不一样了。所以最终是看rotation和localRotation的实际值来决定。

 

 一些用法

1) 使用四元数计算相机的forward向量

var myForward = this.transform.rotation * Vector3.forward;
myForward.Normalize();
Debug.Log($"{myForward.x}, {myForward.y}, {myForward.z}");

var f = this.transform.forward; //上面的结果和这边得到的是一样的
Debug.Log($"{f.x}, {f.y}, {f.z}");

 

2) 相机绕着player旋转

 

using UnityEngine;

[RequireComponent(typeof(Camera))]
public class RotateAround : MonoBehaviour
{

    private Transform m_Camera;

    public Transform m_Player;

    public Vector3 m_OffsetPoint = new Vector3(0.0f, 0.0f, -5.0f);

    private float m_HorizontalAngle = 0.0f;

    void Awake()
    {
        m_Camera = GetComponent<Camera>().transform;
    }

    void Update()
    {
        if (m_Player == null) return;

        if (Input.GetMouseButton(0))
        {
            m_HorizontalAngle += 0.1f;
        }
        else if (Input.GetMouseButton(1))
        {
            m_HorizontalAngle -= 0.1f;
        }

        Quaternion cameraRot = Quaternion.Euler(0, m_HorizontalAngle, 0);
        m_Camera.rotation = cameraRot;

        //# m_OffsetPoint到原点的距离为旋转半径
        //# 如果不加m_Player.position就是绕着原点旋转,加了就是绕着Player旋转。
        m_Camera.position = m_Player.position + cameraRot * m_OffsetPoint; 
    }

}

 

posted @ 2023-04-15 23:36  yanghui01  阅读(38)  评论(0编辑  收藏  举报