Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Question Rotate a game object around another game object x amount of times

Discussion in '2D' started by GarrettDR, Apr 25, 2022.

  1. GarrettDR

    GarrettDR

    Joined:
    Feb 24, 2019
    Posts:
    9
    I have a collider that that I want to rotate around a game object for x amount of times. I am using this line in Update to rotate the collider:

    Code (CSharp):
    1.                 col.transform.RotateAround(this.transform.position, new Vector3(0, 0, 1), Time.deltaTime * 100);
    I know I could use a boolean, or a counter, but I do not know how to implement it. Please someone point me in the direction I need. I am here to learn, just asking someone who know more than me!

    Thanks!
     
  2. GarrettDR

    GarrettDR

    Joined:
    Feb 24, 2019
    Posts:
    9
    Any idea would be welcome. Please if someone can tell me what I am missing I would be truly grateful!
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    Generally with rotation, you want to be the one tracking the degrees, NEVER relying on reading data back from .eulerAngles and modifying it. Here's why:

    https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html

    A solution to rotate any object AROUND another can also be accomplished by placing an invisible proxy object at the center of the rotation, then making the object you want to rotate be a child of it, and rotating the proxy object.

    Try this:

    Make 2 spheres, separated by a bit: Earth and Moon

    Make an invisible GameObject called Proxy, located exactly where the earth is in space (not parented)

    Make the moon a child of the proxy

    Now spin the proxy to make the moon go around the earth X times.

    Code (csharp):
    1. public Transform ProxyTransform;  //drag the proxy in here!
    2.  
    3. private int NumberOfOrbits = 3;
    4. private float AngularRate = 200; // degrees per second
    5. private float Angle;
    And then in Update:

    Code (csharp):
    1. void Update()
    2. {
    3.   // advance around
    4.   Angle += AngularRate * Time.deltaTime;
    5.  
    6.   // STOP after the requisite count of orbits
    7.   if (Angle >= 360.0f * NumberOfOrbits)
    8.   {
    9.     Angle = 360.0f * NumberOfOrbits;
    10.   }
    11.  
    12.   // spin the proxy and the moon will come with it
    13.   ProxyTransform.rotation = Quaternion.Euler( 0, 0, Angle);
    14. }