Animating the moon orbit
OK, back to work. With that short explanation of Unity programming, we're better armed to write more code. Let's get the moon moving; it should be orbiting the earth.
Adding the moon orbit
Let's write a script called Orbit
that rotates one object, the moon, around another object, the earth. We want to be able to specify its orbital period as the number of earth days for one complete orbit. For the moon, that's 27.3 days. And, like our Spin
script, we'll also provide a scalar that converts earth days into game time seconds as shown ahead:
- In
Hierarchy
, selectMoon
andAdd Component, New Script (C-Sharp).
Name itOrbit
, then pressCreate and Add.
- Double-click on the new script to open it in your code editor.
Write the Orbit
class as follows:
File: Orbit.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Orbit : MonoBehaviour { public Transform aroundBody; public float orbitalPeriod = 27.3f; // earth days for one...