四元数百度百科: 传送门
四元数官方文档: 传送门
欧拉旋转、四元数、矩阵旋转之间的差异: 传送门
四元数转换为欧拉角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 initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.Space)) { //获得游戏物体欧拉角 print(cube.eulerAngles); //获得游戏物体四元数 print(cube.rotation); } } }
Quaternion.cs
欧拉角:方便开发者在控制面板上观察游戏物体旋转的角度,但旋转轴固定
四元数:旋转轴可以是任意向量 传送门
//获得游戏物体欧拉角 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 initialization void Start () { } // Update is called once per frame void Update () { //让player前方向和dir方向保持一致 Vector3 dir = player.position - enemy.position; player.rotation = Quaternion.LookRotation(dir); } }
Quaternion_Gary
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 initialization void Start () { } // Update is called once per frame void Update () { //让player前方向和dir方向保持一致 Vector3 dir = player.position - enemy.position; Quaternion target = Quaternion.LookRotation(dir); player.rotation = Quaternion.Slerp(player.rotation,target,Time.deltaTime); } }
Quaternion_Gary.cs
void Update () { //让player前方向和dir方向保持一致 Vector3 dir = player.position - enemy.position; Quaternion target = Quaternion.LookRotation(dir); player.rotation = Quaternion.Slerp(player.rotation,target,Time.deltaTime); }
原文地址:https://www.cnblogs.com/1138720556Gary/p/9941272.html
时间: 2024-11-08 09:25:06