天天看點

Unity3D之四元數運算

一,四元數 * 向量 = 向量

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

        2⃣️,實驗設計

                1,設計遊戲場景如下:

Unity3D之四元數運算
                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,挂載參數如下

Unity3D之四元數運算

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

Unity3D之四元數運算

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

        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,旋轉分析

Unity3D之四元數運算

繼續閱讀