四元数百度百科: 传送门
四元数官方文档: 传送门
欧拉旋转、四元数、矩阵旋转之间的差异: 传送门
四元数转换为欧拉角eulerAngles 官方文档: 传送门
欧拉角转换为四元数Euler 官方文档: 传送门
Quaternion.LookRotation 官方文档:传送门
LookRotation()根据对局部坐标轴的描述, 构造对应的代表旋转程度的四元数
一、Transform中四元数和欧拉角
using System.Collections; using System.Collections.Generic; using UnityEngine;public class Quaternion : MonoBehaviour {public Transform cube;// Use this for initializationvoid Start () {}// Update is called once per framevoid Update () {if (Input.GetKeyDown(KeyCode.Space)){//获得游戏物体欧拉角 print(cube.eulerAngles);//获得游戏物体四元数 print(cube.rotation);}} }
欧拉角:方便开发者在控制面板上观察游戏物体旋转的角度,但旋转轴固定
四元数:旋转轴可以是任意向量 传送门
//获得游戏物体欧拉角 print(cube.eulerAngles);//获得游戏物体四元数print(cube.rotation);
二、Quaternion.LookRotation
场景中创建一个Capsule作为玩家,Sphere作为敌人,给Capsule绑定Quaternion_Gary.cs脚本,要使玩家一致朝向敌人可以用LookRotation()来实现
using System.Collections; using System.Collections.Generic; using UnityEngine;public class Quaternion_Gary : MonoBehaviour {public Transform player;public Transform enemy;// Use this for initializationvoid Start () {}// Update is called once per framevoid Update () {//让player前方向和dir方向保持一致Vector3 dir = player.position - enemy.position;player.rotation = Quaternion.LookRotation(dir);} }
void Update () {//让player前方向和dir方向保持一致Vector3 dir = player.position - enemy.position;player.rotation = Quaternion.LookRotation(dir);}
有时以一帧的速度去让玩家转头容易造成不好的体验
延缓转头速度缓慢,让动画看起来更平滑
using System.Collections; using System.Collections.Generic; using UnityEngine;public class Quaternion_Gary : MonoBehaviour {public Transform player;public Transform enemy;// Use this for initializationvoid Start () {}// Update is called once per framevoid Update () {//让player前方向和dir方向保持一致Vector3 dir = player.position - enemy.position;Quaternion target = Quaternion.LookRotation(dir);player.rotation = Quaternion.Slerp(player.rotation,target,Time.deltaTime);} }
void Update () {//让player前方向和dir方向保持一致Vector3 dir = player.position - enemy.position;Quaternion target = Quaternion.LookRotation(dir);player.rotation = Quaternion.Slerp(player.rotation,target,Time.deltaTime);}