一、动作控制:3、旋转与Quaternion类详解
2022-02-13 本文已影响0人
GameObjectLgy
1、Transform、rotation、eulerAngles关系
Transform里包含了rotation变量和eulerAngles
rotation里有包含了eulerAngles变量
使用示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QuaternionTest : MonoBehaviour
{
public Transform A, B;
public Quaternion rotation = Quaternion.identity;
Vector3 eulerAngle = Vector3.zero;
float speed = -10.0f;
float tSpeed = 0.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
tSpeed += speed * Time.deltaTime;
//第一种方式:将Quaternion实例对象赋值给transform的rotation
rotation.eulerAngles = new Vector3(0.0f, tSpeed, 0.0f);
A.rotation = rotation;
//第二种方式:将三位向量代表的欧拉角直接赋值给transform的eulerAngle
B.eulerAngles = new Vector3(0.0f, tSpeed, 0.0f);
}
}
2、关键成员方法(1)LookRotation
public static Quaternion LookRotation(Vector3 forward);
public static Quaternion LookRotation(Vector3 forward, [DefaultValue("Vector3.up")] Vector3 upwards);
public class Quaternion_LookRotation_Test2 : MonoBehaviour
{
public Transform target;
void Update()
{
Vector3 relativePos = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
transform.rotation = rotation;
}
}
3、关键成员方法(2)RotateTowards
public static Quaternion RotateTowards(Quaternion from, Quaternion to, float maxDegreesDelta);
按步长匀速旋转到指定的旋转角度
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Quaternion_RotateTowards_Test4 : MonoBehaviour
{
public Transform target;
public float speed;
void Update()
{
float step = speed * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, target.rotation, step);
}
}
3、关键成员方法(3)Lerp 和 Slerp
public class Quaternion_Lerp_Test3 : MonoBehaviour
{
public enum RotateType
{
Lerp,
Slerp
}
public RotateType type;
public Transform from;
public Transform to;
public float speed = 0.1F;
void Update()
{
//将自己的转向转到与to的方向一致
if (type == RotateType.Lerp)
{
transform.rotation = Quaternion.Lerp(from.rotation, to.rotation, Time.time * speed);//(匀速)
}
else
transform.rotation = Quaternion.Slerp(from.rotation, to.rotation, Time.time * speed);//(球型插值,最适合旋转)
}
}
4、Quaternion对象与Vector3对象相乘
用于自身移动变换
transform.position += tansform.rotation * A;
其中A为Vector3的对象。transform对应的对象会沿着自身坐标系中向量A的方向移动A的模长的距离。transform.rotation与A相乘可以确定移动的方向和距离。