Unity3D: Moving a child to orbit a parent

1.1k Views Asked by At

I have made a game where I make two spheres, one child sphere and one parent sphere. The parent sphere is bigger than the child sphere, and I am trying to make the child move around the parent sphere.

In the following code, the child sphere moves in a circle. The problem is that it does not move in relation to the parent, so whenever I move the parent of the object, the child stays and no longer moves around the parent, but rather moves freely. I accept that this is a lot to ask, but if someone could contribute, it would be greatly appreciated. Here is the code I have which moves the sphere (not in relation to the parent object):

void Update(){
    timeCounter += Input.GetAxis("Horizontal") * Time.deltaTime; 
    float x = Mathf.Cos (timeCounter);
    float y = Mathf.Sin (timeCounter);
    float z = 0;
    transform.position = new Vector3 (x, y, z);
}

I also intend to move the parent sphere and I expect the child sphere to follow and still move in relation to the parent sphere.

1

There are 1 best solutions below

1
On BEST ANSWER

whenever I move the parent of the object, the child stays and no longer moves around the parent

Thats because you are moving the sphere via

transform.position

when it should be

transform.localPosition

Either that or you could do

transform.position = transform.parent.position + new Vector3 (x, y, z); 

EDIT: personally, i would do the latter and not even parent the sphere, that way you can rotate the mother sphere or manipulate it independantly without effecting the other sphere in weird ways