Rotating the earth

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:

  1. 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:

  1. Double-click on the Spin script to open it in your editor.
Depending on how you install Unity, the default editor for program scripts may be either MonoDevelop or Visual Studio. Either is fine. Unity creates an empty script from a default template.

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).

  1. After making the edits, save the file.
  2. Back in Unity, press Play and point the camera to your marker to watch the globe rotate.
If the script has any errors, Unity will report these to you in the Console window. Be sure to have the Console window visible (Window | Console) so you can know whether you have made any typos or other mistakes while writing your script.
  1. Now, for a little bit of cleanup, in the Project window, drag the Spin script from Assets/ to the Assets/SolarSystem/Scripts folder.
  2. Save the scene and the project.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset