Unity3D: Moving a Child into Parent Orbit

I have created a game in which I make two spheres, one child sphere and one parent sphere. The parent sphere is larger than the child sphere and I am trying to get the child to navigate the parent sphere.

The following code moves the child sphere in a circle. The problem is that it doesn't move in relation to the parent, so whenever I move the parent, the child stays and no longer moves over the parent, but moves freely. I accept this is a lot to ask, but if someone could contribute they would greatly appreciate it. Here is the code I have that moves the sphere (not relative to its parent):

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.

+3


source to share


1 answer


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

This is because you move the sphere through

transform.position

      

when should it be



transform.localPosition

      

Either that or you could do

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

      

EDIT: I personally would do the latter and not even give birth to a sphere, this way you can rotate the sphere of matter or manipulate it independently without affecting the other sphere in weird ways.

+5


source







All Articles