围绕球体3D移动立方体

时间:2019-11-29 02:24:51

标签: unity3d

我想绕球体移动一个立方体,初始位置:https://imgur.com/a/MWauISG

当我按向左箭头键时,它会毫无问题地旋转:https://imgur.com/a/Ov8IoFr

我想将其移向该方向:https://imgur.com/a/GsbbKrB

但是它在此曲线上围绕起始线https://imgur.com/a/i0NU09t

移动

您能帮我解决这个问题吗?

using UnityEngine;

public class SphericController : MonoBehaviour
{

   public float radius = 1.05f;
   public float translateSpeed = 180.0f;
   public float rotateSpeed = 360.0f;

   float angle = 0.0f;
   Vector3 direction = Vector3.one;
   Quaternion rotation = Quaternion.identity;
   void Update()    
   {
        direction = new Vector3(Mathf.Sin(angle), Mathf.Cos(angle));

      // Rotate with left/right arrows
        if (Input.GetKey(KeyCode.LeftArrow))  {
           Rotate( rotateSpeed);
       }
        if (Input.GetKey(KeyCode.RightArrow)) Rotate(-rotateSpeed);

      // Translate forward/backward with up/down arrows
        Translate(0,  translateSpeed);

        UpdatePositionRotation();
    }
   void Rotate(float amount)
    {
        angle += amount * Mathf.Deg2Rad * Time.deltaTime;
    }

    void Translate(float x, float y)
    {
        var perpendicular = new Vector3(-direction.y, direction.x);
        var verticalRotation = Quaternion.AngleAxis(y * Time.deltaTime, perpendicular);

        //var horizontalRotation = Quaternion.AngleAxis(x * Time.deltaTime, direction);
        rotation *=  verticalRotation;
    }

    void UpdatePositionRotation()
    {
        transform.localPosition = rotation * Vector3.forward * radius;
        transform.rotation = rotation * Quaternion.LookRotation(direction, Vector3.up);
    }
}

0 个答案:

没有答案
相关问题