Unity3D之四元數運算

一,四元數 * 向量 = 向量

        1⃣️,意義:爲向量做一個偏移(爲向量做一個旋轉)

        2⃣️,實驗設計

                1,設計遊戲場景如下:

B01.png

                2, 編寫腳本如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Q2VDemo : MonoBehaviour
{
    [SerializeReference]
    private float angleY;
    [SerializeReference]
    private float distance;
    //目標點
    private Vector3? targetVec;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {
             this.targetVec = Quaternion.Euler(0, this.angleY, 0) * this.transform.forward * this.distance + this.transform.position;
        }
        if (this.targetVec != null) {
            Debug.DrawLine(this.transform.position, (Vector3)this.targetVec);
        }
    }
}

            解析:1,this.transform.forward 得到的是GO本地座標(0,0,1)的點在世界座標中的位置

                       2,this.transform.forward * this.distance 既是 GO本地座標(0,0,10)的點在世界座標中的位置

                       3,Quaternion.Euler(0, this.angleY, 0) * this.transform.forward * this.distance 將第2步的座標沿Y軸旋轉this.angleY度

            3,分析如下圖

                  a,掛載參數如下

B02.png

                                根據左手定則,可以得到一個藍色虛線,目標點在這個虛線上。如下

B03.png


二,四元數 * 四元數 = 四元數

        1⃣️, 意義: 旋轉的組合(旋轉的疊加)

        2⃣️, 實驗設計:

                 1,還是參照上一個場景                 

                 2,代碼更改如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Q2VDemo : MonoBehaviour
{
    [SerializeReference]
    private float angleY;
    [SerializeReference]
    private float angleX;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {
            this.transform.rotation *= Quaternion.Euler(0, this.angleY, 0) * Quaternion.Euler(this.angleX, 0, 0);
        }
    }
}

            解析:1,Quaternion.Euler(0, this.angleY, 0) * Quaternion.Euler(this.angleX, 0, 0)   Y軸旋轉疊加X軸的旋轉

                       2,*= 最後疊加GO本身的旋轉

                3,旋轉分析

B04.png

                            解析:1,第一步沿着Y軸旋轉30度, 綠色表示

                                       2,第二步沿着X軸旋轉30度, 紅色表示

                                       3, 疊加GO本身旋轉 *= 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章