欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity高*度轨道旋转

程序员文章站 2022-07-14 16:50:54
...

一个物体围绕另一个物体旋转,仿天体公转的效果,可以动态的*调节公转轨道及公转半径。


动态效果图:

Unity高*度轨道旋转


Unity高*度轨道旋转


Unity高*度轨道旋转



可调节参数:

Unity高*度轨道旋转


RevolutionTarget:围绕旋转的目标

RevolutionSelf:围绕旋转的物体

XDeviation:轨道进行X轴偏移

YDeviation:轨道进行Y轴偏移

ZDeviation:轨道进行Z轴偏移

XRotateSpeed:X轴旋转半径(为负时反向转动)

YRotateSpeed:Y轴旋转半径

ZRotateSpeed:Z轴旋转半径

RevolutionSpeed:转动速度

ShowGizmos:是否在scene显示当前轨道


圆形轨道:(三个轴轨道半径相同时为圆形轨道)

Unity高*度轨道旋转


椭圆轨道:(三个轴轨道半径不同时为椭圆轨道)

Unity高*度轨道旋转


轨道偏移:(仿地球公转效果)

Unity高*度轨道旋转


核心代码,主要就是三角函数计算,逻辑很简单:

        _Angle += RevolutionSpeed * Time.deltaTime;
        if (_Angle > 360) _Angle -= 360;

        float x = RevolutionTarget.position.x + XDeviation + Mathf.Cos(_Angle * (Mathf.PI / 180)) * _radius * XRotateSpeed;
        float y = RevolutionTarget.position.y + YDeviation + Mathf.Sin(_Angle * (Mathf.PI / 180)) * _radius * YRotateSpeed;
        float z = RevolutionTarget.position.z + ZDeviation + Mathf.Sin(_Angle * (Mathf.PI / 180)) * _radius * ZRotateSpeed;

        RevolutionSelf.position = new Vector3(x, y, z);

编辑器中的轨道绘制:

    private void OnDrawGizmos()
    {
        if (!ShowGizmos || RevolutionTarget == null || RevolutionSelf == null)
            return;
        
        //绘制目标线
        Gizmos.color = Color.red;
        Gizmos.DrawLine(RevolutionTarget.position, RevolutionSelf.position);

        //绘制轨道
        Gizmos.color = Color.blue;
        float sub = 0.1f;
        float i = 0;
        //轨道起点
        float x = RevolutionTarget.position.x + XDeviation + _radius * Mathf.Cos(i) * XRotateSpeed;
        float y = RevolutionTarget.position.y + YDeviation + _radius * Mathf.Sin(i) * YRotateSpeed;
        float z = RevolutionTarget.position.z + ZDeviation + _radius * Mathf.Sin(i) * ZRotateSpeed;
        Vector3 sPoint = new Vector3(x, y, z);
        Vector3 ePoint = Vector3.zero;
        for (i += sub; i <= Mathf.PI * 2; i += sub)
        {
            x = RevolutionTarget.position.x + XDeviation + _radius * Mathf.Cos(i) * XRotateSpeed;
            y = RevolutionTarget.position.y + YDeviation + _radius * Mathf.Sin(i) * YRotateSpeed;
            z = RevolutionTarget.position.z + ZDeviation + _radius * Mathf.Sin(i) * ZRotateSpeed;
            ePoint = new Vector3(x, y, z);
            Gizmos.DrawLine(sPoint, ePoint);
            sPoint = ePoint;
        }
        //轨道终点
        x = RevolutionTarget.position.x + XDeviation + _radius * Mathf.Cos(Mathf.PI * 2) * XRotateSpeed;
        y = RevolutionTarget.position.y + YDeviation + _radius * Mathf.Sin(Mathf.PI * 2) * YRotateSpeed;
        z = RevolutionTarget.position.z + ZDeviation + _radius * Mathf.Sin(Mathf.PI * 2) * ZRotateSpeed;
        ePoint = new Vector3(x, y, z);
        Gizmos.DrawLine(sPoint, ePoint);
    }


github源码链接:https://github.com/SaiTingHu/Revolution