Search Unity

Editing Child Position from Parent

Discussion in 'Scripting' started by KarneeKarnay, Jan 27, 2013.

  1. KarneeKarnay

    KarneeKarnay

    Joined:
    Sep 3, 2012
    Posts:
    61
    I've been working on a rotating sphere. I placed the sphere as a child of a empty game object and set it to rotate. I would like to change the distance between the sphere and the parent though. This is the code I'm using.


    Code (csharp):
    1.     public float speed = 0.8f;
    2.     public float radius = 10f;
    3.     private GameObject sphere;
    4.    
    5.     // Update is called once per frame
    6.     void Update () {
    7.        
    8.         sphere = GameObject.Find("Sphere");
    9.         //sphere.transform.position = new Vector3 (transform.position.x, transform.position.y , radius);
    10.        
    11.         transform.Rotate(new Vector3(0, speed, 0));
    12.        
    13.         //Debug.Log(transform.rotation.y.ToString());
    14.    
    15.     }
    What currently happens is that the sphere gets stuck at a position and the empty game object moves around the sphere. I know this isn't the right way but I seem to be stuck in idiot mode for now. Please help!
     
  2. Timer

    Timer

    Joined:
    Jan 14, 2013
    Posts:
    35
    Your problem is not clear,

    if you wanna rotate something, you wanna rotate it about a point(Vector3 position) and along any particular axis(Vector3 direction)

    like if you wanna rotate something about its center(postion) like its spinning (direction is Vector3.up)
    simply use:
    transform.Rotate, just like you did.

    if you make any object child of this object (the object that is rotating), it will also rotate about the position of parent.

    OR

    you can choose the center(position) as a transform (drag any gameObject in the inspector), then to rotate it around that center(lets say center.position) and about Up axis:

    transform.RotateAround (center.position, Vector3.up, speed * Time.deltaTime);

    don't forget to multiply your speed with Time.deltaTime.
     
  3. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    In your scenario the length of sphere's transform.localPosition would equal the radius. So all you need to do is change its mangitude without changing its direction.

    Or, in code:
    Code (csharp):
    1.  
    2. public float speed = 0.8f;
    3. public float radius = 10f;
    4. private GameObject sphere;
    5.  
    6. void Update()
    7. {
    8.   sphere = GameObject.Find("Sphere");
    9.   sphere.transform.localPosition = sphere.transform.localPosition.normalized * radius;
    10.  
    11.   // the rest of your code goes here.
    12. }
    That should do it.
     
  4. KarneeKarnay

    KarneeKarnay

    Joined:
    Sep 3, 2012
    Posts:
    61
    Thanks for the response guys.

    shaderop your code fixed my problem. Thanks very much. :)