Unity 绕轴旋转 Unity之绕轴进行旋转的操作

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Unity 绕轴旋转 Unity之绕轴进行旋转的操作

风中追风3zZ   2021-04-12 我要评论
想了解Unity之绕轴进行旋转的操作的相关内容吗,风中追风3zZ在本文为您仔细讲解Unity 绕轴旋转的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Unity,绕轴进行旋转,绕轴旋转,下面大家一起来学习吧。

先上一张效果图

using UnityEngine;
using System.Collections;
public class TestRotateRound : MonoBehaviour
{
    public GameObject Sphere;
    private float curtTime = 0.0f;
    void Update()
    {
        //使用C#封装好的代码RotateAround
        gameObject.transform.RotateAround(Sphere.transform.position, Sphere.transform.up, 72 * Time.deltaTime);
        //自己封装代码,功能和上面的相同
        //RotateAround(Sphere.transform.position,Vector3.up, 72 * Time.deltaTime);
    }
    private void RotateAround(Vector3 center, Vector3 axis, float angle)
    {
        //绕axis轴旋转angle角度
        Quaternion rotation = Quaternion.AngleAxis(angle, axis);
        //旋转之前,以center为起点,transform.position当前物体位置为终点的向量.
        Vector3 beforeVector = transform.position - center;
        //四元数 * 向量(不能调换位置, 否则发生编译错误)
        Vector3 afterVector = rotation * beforeVector;//旋转后的向量
        //向量的终点 = 向量的起点 + 向量
        transform.position = afterVector + center;
        //看向Sphere,使Z轴指向Sphere
        transform.LookAt(Sphere.transform.position);
    }
}

补充:Unity绕x轴旋转并限制角度的陷阱

在制作FPS相机时,遇到了需要限制角度的需求,视角只能查看到-60到60度的范围,而在Unity的Transform组件中,绕x轴逆时针旋转,Transform组件的localEulerAngle会在0~360范围内递增(如图)

关键在于其中的角度转换,直接上代码

        public static void RotateClampX(this Transform t, float degree, float min, float max)
        {
            degree = (t.localEulerAngles.x - degree);
            if (degree > 180f)
            {
                degree -= 360f;
            }
            degree = Mathf.Clamp(degree, min, max);
            t.localEulerAngles = t.localEulerAngles.SetX(degree);
        }

补充:Unity3D 实现物体始终面向另一个物体(绕轴旋转、四元数旋转)

一开始本人纠结于在VR中,怎么利用手柄来控制物体的旋转,物体位置不变。

相当于:地球仪。更通俗点来说,就是一个棍子插到地球仪上,然后拿着棍子就可以控制地球仪转。手柄相当于那根棍子。

代码如下:

myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);

这句代码实现了 myTransform 始终可以根据 target 旋转,rotationSpeed控制速度。

当然上面这句话仅仅只是始终面向,还没有加上一开始记录下target的初始旋转。不然一开始就要跟着手柄转,而不是自己随意控制。对于上句的理解,我理解完便贴上。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们