Ceci est une ancienne révision du document !


Get an offline copy of this page by clicking the libreoffice writer icon Exporter la page au format Open Document

Moving objects : Earth is turning

We’ve already seen what a GameObject is in Unity, and we’ve even created our first GameObject (it was a 3D model of the Earth).

In the editor (Unity’s graphical user interface), you can hide an existing GameObject by unchecking the checkbox located right next to the GameObject’s name. The GameObject will then not be displayed on the screen.

You can also do this using code.

Creating Your First C# Script

We’re going to create our first C# script, which will allow us to hide the ground by pressing the spacebar, for example.

In the root of the Assets folder, create a new subfolder and name it “Scripts.”

Double-click the Scripts folder to open it, and create a new C# script that you'll name “EarthManager.cs”.

Unity does not have a built-in code editor, so you are free to choose your preferred editor (Visual Studio, Visual Studio Code, Notepad++, etc.). Normally VisualStudio should have been installed with unity and the CS files will be manage by VSCode.

I recommend Visual Studio Code because it supports syntax highlighting, IntelliSense/AI (auto-completion), precompilation, and even debugging. For debugging, you’ll need to install this VSCode extension provided by Unity: https://marketplace.visualstudio.com/items?itemName=Unity.unity-debug

You can change the default code editor by going to the Edit / Preferences / External Tools menu.

Structure of a C# script

Double-click the script, and it will open in the default editor set in Unity (Visual Studio Code in my case).

By default, all Unity C# scripts inherit from the MonoBehavior class. Thanks to this base class, you can drag and drop your scripts onto a GameObject to attach them to it.

public class earthManager : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
 
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
}

This script template already includes two methods:

  • Start(): The code declared in this method will be executed only once at startup.
  • Update(): The code declared in this method will be executed in a loop—roughly 30 times per second, to put it simply.

Attaching a C# Script to a GameObject

Scripts can be attached to a GameObject. This allows you to add behaviors to a GameObject. To add the first behavior to our Earth, we’ll drag and drop our “EarthManager” script onto the “Earth” GameObject.

Now that the script is attached to the GameObject, we're going to code the desired behavior.

using UnityEngine;
 
public class EarthManager : MonoBehaviour
{
    // Start is called only once
    private void Start()
    {
 
    }
 
    // Update is called every frame
    // i.e., 30 times per second if the game is running at 30 frames per second
    private void Update()
    {
        // if the spacebar is pressed
        if (Input.GetKeyDown(“space”))
        {
            // log a message to the console
            Debug.Log(“The spacebar was pressed”);
 
            // `this` represents the script instance
            // `this.gameObject` provides access to the script's GameObject
            // `activeSelf` indicates the GameObject's visibility
            bool isActive = this.gameObject.activeSelf;
            if (isActive)
            {
                // if the GameObject is active (visible)
                Debug.Log(“Hiding the ‘earth’ GameObject”);
 
                // set the GameObject to inactive (hide it)
                this.gameObject.SetActive(false);
            }
        }
    }
}

To test our code, we're going to run our game in the editor:

If you press the spacebar, you'll notice that the Earth disappears (it is no longer displayed by the render engine because its GameObject's visibility is turned off).

Stay in Play mode (with the Game tab active), select the Earth GameObject in the hierarchy on the left if you haven’t already, and check the status of the GameObject’s visibility checkbox in the Inspector on the right.

The interface reflects the changes made by the running code when you are in Play mode. This provides a basic level of visual debugging within the editor.

When you deactivate a GameObject, all scripts attached to it stop running.

Debug.Log statements write a log to the editor console. These logs are a starting point for debugging; they let you know which lines of code have been executed and even display the values of variables.

The Earth rotates...

We’re going to add a second behavior to our planet (in addition to the one that already exists). In addition to hiding the Earth when the spacebar is pressed, we’re going to make it rotate on its axis.

Create a new script in Assets/Scripts and name it “EarthRotation.cs”. Copy and paste the code below into your script.

using UnityEngine;
 
public class EarthRotation : MonoBehaviour
{
    public Vector3 localRotationSpeed;
 
    // Start is called before the first frame update
    private void Start()
    {
 
    }
 
    // Update is called once per frame
    private void Update()
    {
        this.transform.Rotate(localRotationSpeed * Time.deltaTime, Space.Self);
    }
}

Drag and drop the “EarthRotation” script onto the “Earth” GameObject. The script is attached to the GameObject, right below the previous one (EarthManager). The script exposes a public variable named “LocalRotationSpeed” that allows you to customize the rotation speed and axis. Set the Y-axis to 50.

This variable is of type Vector3, meaning it’s a 3-dimensional vector that can store a value for the X axis, a value for the Y axis, and a value for the Z axis. Vectors are very useful; we’ll come back to them later.

Run your game (using the Play button); the Earth rotates on its axis at a speed of 50 along the Y-axis. If you press the spacebar, it continues to disappear.

In the editor, you can see in real time that your script is changing the GameObject’s rotation along the Y-axis.

Conclusion

Using two small C# scripts, we were able to add two different behaviors to our “Earth” GameObject. These scripts can be reused indefinitely; you can apply them to other GameObjects (this will create multiple instances of the same script).

Exercise

  1. Add a Milky Way skybox; to do this, use the Asset Store (Milky Way Skybox)
  2. Make the moon rotate on its axis
  3. Make the moon orbit the Earth
  4. Make the camera rotate around the Earth in the opposite direction; the camera must always be oriented toward the center of the Earth

brasil/courses/blender_unity/unity/4_moving_objects.1787676821.txt.gz · Dernière modification : de yann
CC Attribution-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0