Make GameObject rotate around another around random axis but with fixed distance
I am trying to create a sphere/planet with a smaller sphere/moon that should rotate around the centre of the planet, at a fixed distance (orbital height). What's more, I want the moon to follow the planet, the movement of which will be controlled by the player.
I wrote the following code to achieve this (I haven't implemented the player controls yet).
For the planet:
public class Planet : MonoBehaviour {
public GameObject moonPrefab;
public float moonOrbitalSpeed;
public float orbitalHeight;
GameObject moon;
void Awake() {
moon = Instantiate(moonPrefab, transform.position + orbitalHeight * RandomNormalizedAxis(), Quaternion.identity) as GameObject;
moon.GetComponent<MoonOrbit>().planet = gameObject;
moon.GetComponent<MoonOrbit>().orbitalSpeed = moonOrbitalSpeed;
moon.transform.SetParent(transform);
}
Vector3 RandomNormalizedAxis() {
return new Vector3(
Random.Range(-1f, 1f),
Random.Range(-1f, 1f),
Random.Range(-1f, 1f)
).normalized;
}
}
For the moon:
public class MoonOrbit : MonoBehaviour {
[HideInInspector] public GameObject planet;
[HideInInspector] public float orbitalSpeed;
Vector3 axis;
void Start() {
axis = RandomAxis();
}
void FixedUpdate() {
transform.RotateAround(planet.transform.localPosition, axis, orbitalSpeed * Time.fixedDeltaTime);
}
Vector3 RandomAxis() {
return new Vector3(
Random.Range(-1f, 1f),
Random.Range(-1f, 1f),
Random.Range(-1f, 1f)
);
}
}
But I see the strangest results in the editor:
As you can see, not only the moon rotates around a point somewhere above the surface on the planet, but the planet transform seems to move (kinda "shake") in the scene, too (it is the axis system shown that is visible in the gif), even though the coordinates of the planet transform in the inspector stay the same! (0, 0, 0, both globally and locally, it is not included in the gif above).
Can somebody please help me understand what exactly I am missing here?
(PS. Tried with transform.position
instead of transform.localPosition
, but nothing changed)
Your answer
Follow this Question
Related Questions
Why my RotateAround() function doesn't work? 0 Answers
Rotate an Object while moving forward using empty gameObject 0 Answers
Mixing transform.rotation and transform.rotate? 1 Answer
Rotating Camera around Player's X-axis while rotating Player around its Y-axis (using mouse input) 0 Answers
How to rotate an object according to the camera's view? 1 Answer