旋转与Quaternion类详解

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相乘可以确定移动的方向和距离。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值