Unity踩坑笔记 - 四元数旋转(以骨骼为例)

Unity踩坑笔记 - 四元数旋转(以骨骼为例)


以下内容仅为学习参考、学习笔记使用、欢迎评论区留言纠错

前言

旋转一直都是头痛的问题。左手系还是右手系,外旋还是内旋,世界还是局部坐标。旋转的形式选哪一个,稍有不慎就会出差池。像骨骼的话还有相对于父关节的相对数据,这种数据动作发生变化,关节坐标系也有可能发生变化。因此最简单的还是世界坐标,这就必须严格要求被旋转物体的摆放位置。
旋转形式有很多种,这里选择的旋转形式是欧拉角和四元数,欧拉角是最容易获得的数据。

场景设置

首先查看avatar的位置
在这里插入图片描述
这里选择LeftUpperArm的关节做演示,可以发现世界坐标和局部坐标的不同。

局部旋转测试

这是本地旋转测试,绕本地z旋转

public class test : MonoBehaviour
{
    
    
    Animator animator;
    float deltaz = 0f;
    Vector3 upperArm = new Vector3(0f, 0f, 0f);
    Quaternion prevQ;

    void Start()
    {
    
    
       
        // 获取动画控件
        animator = this.GetComponent<Animator>();
        // 获取原始旋转
        prevQ = animator.GetBoneTransform(HumanBodyBones.LeftUpperArm).rotation;
        Quaternion currentQ = Quaternion.Euler(upperArm.x, upperArm.y, upperArm.z);
        animator.GetBoneTransform(HumanBodyBones.LeftUpperArm).rotation = currentQ * prevQ;
    }

    // Update is called once per frame
    void Update()
    {
    
    
        deltaz += 1f;
        upperArm.z = deltaz;
        Quaternion currentQ = Quaternion.Euler(upperArm.x, upperArm.y, upperArm.z);
        animator.GetBoneTransform(HumanBodyBones.LeftUpperArm).rotation =  prevQ * currentQ;
    }
}

在这里插入图片描述

  • 如果局部坐标系发生改变,结果也会发生改变,见下图

在这里插入图片描述

世界旋转测试

这是世界旋转测试,代码只是略微有些不一样。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour
{
    
    
    Animator animator;
    float deltaz = 0f;
    Vector3 upperArm = new Vector3(0f, 0f, 0f);
    Quaternion prevQ;

    void Start()
    {
    
    
       
        // 获取动画控件
        animator = this.GetComponent<Animator>();
        // 获取原始旋转
        prevQ = animator.GetBoneTransform(HumanBodyBones.LeftUpperArm).rotation;
        Quaternion currentQ = Quaternion.Euler(upperArm.x, upperArm.y, upperArm.z);
        animator.GetBoneTransform(HumanBodyBones.LeftUpperArm).rotation = currentQ * prevQ;
    }

    // Update is called once per frame
    void Update()
    {
    
    
        deltaz += 1f;
        upperArm.z = deltaz;
        Quaternion currentQ = Quaternion.Euler(upperArm.x, upperArm.y, upperArm.z);
        animator.GetBoneTransform(HumanBodyBones.LeftUpperArm).rotation = currentQ * prevQ ;
    }
}


在这里插入图片描述

相关阅读

https://blog.csdn.net/weixin_42348363/article/details/113685507
https://blog.csdn.net/weixin_44739495/article/details/110680128

更新

本篇只演示单级旋转操作, 下篇记录多级物体的旋转处理方式。

猜你喜欢

转载自blog.csdn.net/qq_43544518/article/details/125866072