- Home /
Rotating a child around its parent
I've got a small sphere that's parented to a larger sphere and I just need it to rotate around the larger sphere's z-axis, kind of like how the moon rotates around the earth. I can get it to rotate around its own axis, but I'm not sure how to rotate around the parent's.
Answer by synapsemassage · May 19, 2011 at 11:21 AM
make a empty gameobject, place it at the parent's position. make the empty gameobject a child of the parent object. make the moon a child of the empty gameobject. rotate the empty gameobject around z. the child (moon) will follow.
This method is much faster than trying to derive the rotation of the moon on it's own. The extra game object is essentially adding an extra 4 dimensions to make the rotation operation much simpler.
Answer by Mnescat · May 19, 2011 at 11:37 AM
rotations that require a movement component have a center point (in more complicated movements there can be multiple groups you can rotate around at the same time but let's skip that for now)
If you do now know how to create a circular motion around a single point in space you can find the "how to" here: http://unity3d.com/support/documentation/ScriptReference/Transform.RotateAround.html
A sample is given there that uses some basic value which describe your object's orbitpoint
This is the more "correct" way of doing this. It's also the most tidy. +1
For the sake of people co$$anonymous$$g here later, I will expand on this answer:
public void Update()
{
transform.RotateAround(transform.parent.position, new Vector3(0, 1, 0), rotateSpeed * Time.deltaTime);
}
And to deter$$anonymous$$e the distance from the parent object, simply set the transform position relative to the parent
Vector3 childPos = transform.parent.position;
childPos.x -= 0.5f
transform.position = childPos;
You can do this as soon as you have a parent object assigned for the child.
Thanks! I was stuck with rotate and finally found this 3y old reply. Need far more examples in Unity docs.
this helped me, thanks. Not a high enough rating to up-vote yet.
Answer by MAD_dev · May 19, 2011 at 11:01 AM
Since you're comparing to the moon. We only see just a bigger half of the moon while it is rotating. If you want something similar, it's quite easy, although transform.LookAt might not what you need:
void Start(){
GameObject go = GameObject.FindGameObjectWithTag("Earth");
Transform target = go.transform;
}
void Update(){
transform.LookAt(target);
}
Instead you can use if you only want to rotate the z axis (note what's inside the Quaternion.LookRotation function).
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(new Vector3(target.position.x , target.position.y , transform.position.z))), 5 * Time.deltaTime);
Something like that.