Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Moving a cube around sphere 3D

Discussion in 'Scripting' started by MehmetCakir, Nov 29, 2019.

  1. MehmetCakir

    MehmetCakir

    Joined:
    Jul 18, 2017
    Posts:
    5
    Hello all, I want to move a cube around a sphere, initial position:https://imgur.com/a/MWauISG

    when I press left arrow key, it rotates without problem: https://imgur.com/a/Ov8IoFr

    I want to move it to this direction: https://imgur.com/a/GsbbKrB

    But it moves on this curve around starting line: https://imgur.com/a/i0NU09t

    I guess it is because of Quaternion.AngleAxis but I don't know how to solve the problem, can you help me with this problem please?

    Code (CSharp):
    1.  
    2.  
    3.  
    4. using UnityEngine;
    5.  
    6.  public class SphericController : MonoBehaviour
    7. {
    8.     public float radius = 1.05f;
    9.     public float translateSpeed = 180.0f;
    10.     public float rotateSpeed = 360.0f;
    11.  
    12.     float angle = 0.0f;
    13.     Vector3 direction = Vector3.one;
    14.     Quaternion rotation = Quaternion.identity;
    15.     void Update()  
    16.     {
    17.         direction = new Vector3(Mathf.Sin(angle), Mathf.Cos(angle));
    18.         if (Input.GetKey(KeyCode.LeftArrow))
    19.         {          
    20.             Rotate(rotateSpeed);      
    21.         }
    22.         if (Input.GetKey(KeyCode.RightArrow))
    23.         {
    24.             Rotate(-rotateSpeed);
    25.         }
    26.         Translate(0,  translateSpeed);
    27.  
    28.         UpdatePositionRotation();
    29.     }
    30.  
    31.     void Rotate(float amount)
    32.     {
    33.         angle += amount * Mathf.Deg2Rad * Time.deltaTime;
    34.     }
    35.  
    36.     void Translate(float x, float y)
    37.     {
    38.         var perpendicular = new Vector3(-direction.y, direction.x);
    39.         var verticalRotation = Quaternion.AngleAxis(y * Time.deltaTime, perpendicular);
    40.         rotation *=  verticalRotation;
    41.     }
    42.  
    43.     void UpdatePositionRotation()
    44.     {
    45.         transform.localPosition = rotation * Vector3.forward * radius;
    46.         transform.rotation = rotation * Quaternion.LookRotation(direction, Vector3.forward);
    47.     }
    48. }
    49.  
    50.  
     
    Last edited: Nov 29, 2019