Help in C# rotatearound is not around center object
Hi There,
I have a gameobject (B) rotating and rotatingaround another gameobject (A). It is working perfectly. Note A is not moving and B is moving. I have taken this code from (B) and applied it to another gameobject (C). So, gameobject (C) is rotating and rotating around another gameobject (B). Though it works, it is not working as intended. Note B is moving and C is moving. C appears to drift away from B (or vice versa), though B should remain at the center of the rotation axis of C.
I suspect I have introduced some sort of relative positioning snafu or I using the wrong function. I have searched around the forum and are confused with when/how to use quaternion slerp (might be the correct way, just unsure).
Code below.
public class Moon : MonoBehaviour
{
public float MoonRotation = -0.03660100f;
public float MoonOrbitSpeed = 0.03660100f;
public GameObject ObjectEarth;
void Update ()
{
Vector3 MoonOrbitPoint = ObjectEarth.transform.position;
transform.Rotate (new Vector3 (0.0f,MoonRotation*Time.smoothDeltaTime*360.0f,0.0f));
transform.RotateAround (MoonOrbitPoint,new Vector3(0,1,0),MoonOrbitSpeed*Time.smoothDeltaTime*360.0f);
}
}
Thanks Nick
How is the parent child relation? I'd say ever Gameobject should be child of the one it rotates around. If you don't want this cascade you need to keep the distance to the reference gameobject in the code before rotating
Hi hexagonius - good question. I have left the hierarchy not structured. Everything is flat. I suppose I can setup the structure, however this led to other types of problems (i am an obvious novice here). $$anonymous$$y scale, speeds, and distances got messed up quickly (and orbital centers).
In the code above, how would I keep the distance to the reference gameobject in the code before rotating? I only ask because I thought that is what I had done. Could you possibly update/correct the code above or elaborate what is out of sequence?
Separately, is the structuring is best practice? I suppose I should aim to $$anonymous$$imize bad habits.
Separately, is the structuring is best practice?
I like it, and your example is a great reason why. When you want to rotate around the parent (planet), you rotate around your child object's (moon) model-space(localPosition) origin (0,0,0). Now lets say you want to rotate the parent object (planet) around ITS parent(sun). No problem: rotate around your child object's(planet) model-space origin (0,0,0). Everything is going to rotate around only it's parent, and automatically include its parent's movement. There is no need to do any kind of vector subtractions or nested rotations for each "level".