In the previous chapter, we implemented an animation using the Unity graph editors for animator states and animation curves. This time, we will do it using C# scripting.
Earth rotates once a day! (You knew that.) That is about 15 degrees per hour (360/24). If we wanted to go for realism, it might be a little boring to have to watch our model spin at that rate (and when we add the sun, we'd have to wait for a year to watch the animation of a complete orbit). Instead, let's rotate all the way in 24 seconds. That's one game second per real hour.
We'll write a quick script to spin the globe. If you're new to programming, just follow along and then read the introduction to programming in the next section:
- In Hierarchy, select Earth, then in Inspector (you may need to scroll it down), press Add Component, New Script (C-Sharp). Name it Spin and press Create and Add.
The Spin script now appears as a component in the earth's Inspector, as shown in the following screenshot:
- Double-click on the Spin script to open it in your editor.
Edit the file so it looks like this:
File: Spin.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spin : MonoBehaviour { public float gametimePerDay = 24.0f; void Update () { float deltaAngle = (360.0f / gametimePerDay) * Time.deltaTime; transform.Rotate(0f, deltaAngle, 0f); } }
We declared a variable named gametimePerDay with a value of 24 (a float is a number with decimal points versus an integer). Each time the game updates the display, it will rotate the current object by deltaAngle degrees around the y-axis (vertical axis). The deltaAngle attribute is the number of degrees to rotate per game second (360 / gametimePerDay) times the current frame time (Time.deltaTime).
- After making the edits, save the file.
- Back in Unity, press Play and point the camera to your marker to watch the globe rotate.
- Now, for a little bit of cleanup, in the Project window, drag the Spin script from Assets/ to the Assets/SolarSystem/Scripts folder.
- Save the scene and the project.