The best way to explain this is I'm attempting to make a small model solar system (not to scale or anything complicated, just simple rotation as a learning exercise). There's a sun, a planet, and that planet's moon. The planet orbits like normal, however the moon orbiting around the planet shoots off and makes an extremely large and far-away orbit.
My code is as follows (where "target" is the object being orbited around, and "transform" is the orbiting object itself. Both are "Transform" objects.):
public class RotateAndOrbit : MonoBehaviour {
public Transform target;
public float RotationSpeed = 100f;
public float OrbitDegrees = 1f;
void Update () {
transform.Rotate(Vector3.up, RotationSpeed * Time.deltaTime);
transform.RotateAround(target.position, Vector3.up, OrbitDegrees);
}
}
I'm not sure how to compensate for this or even what my mistake is called, but any help would be appreciated.
Answer
Make the moon a child of the planet object, and the planet a child of the star. Now, if the moon wasn't orbiting, it will stay with the planet in its orbit.
You can easily rotate an arbitrary point around another arbitrary point with the following:
public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Quaternion angle) {
return angle * ( point - pivot) + pivot;
}
When everything is set up in the parent/child fashion as I said above, you can easily create a generic script to handle the orbits. Then just drop that script onto the bodies you want to orbit their parents. Update the orbit by adding the rotation for that step:
transform.position =
RotatePointAroundPivot(transform.position,
transform.parent.position,
Quaternion.Euler(0, OrbitDegrees * Time.deltaTime, 0));
No comments:
Post a Comment