天天看点

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之四元数运算

继续阅读