Scripting & Character Movement

Scripting

In order to be able to tell the objects on the scene how to behave, we will have to write some special files, called scripts. These files will be written in C# and will end with the extension .cs. In order to create a such, do the following steps:

  1. Right click in the Project menu
  2. Click Create.
  3. Click C# Script.
  4. Choose a suggestive name.
  5. Press enter.

How to create a script in Unity

By default, each C# Unity script looks like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyFirstScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

Probably you have already noticed the first 3 lines are quite similar. These lines are used in order to include libraries. The syntax is the following: using <library_name>;. A library is a collection of functions we need for our code. For instance, the last included library is UnityEngine. The code we are going to write is in C#. If we want to integrate methods from Unity we need to include UnityEngine library. We can include as many libraries as we want.

The line public class MyFirstScript : MonoBehaviour declares a new class. You don't have to worry about this line too much. All you have to know is that in our example the script should be named MyFirstScript.cs since inside it we have the class MyFirstScript. Inside the class, we always have at least two specific methods: Start() and Update(). Besides these methods, we can create as many as we want.

Start() method is used to initialise the states of objects. This method is called only once at the beginning of the game. Why should we use this method? Some practical examples: we want the score at the beginning of the game to be 0, we want to have maximum health when we start a new level etc.

Update() method is called every frame. If your game runs at 60FPS (frames per second), it means the Update() method is called 60 times per second. Here, we will write everything which should change. For instance, character movement.

Character movement

Now it's time for your first lines of code. Let's begin with basic animations and we character controller. 😎

In computer graphics, as you have seen in the previous videos, there are 3 basic transformations: translation, rotation and scaling. Let's see how can apply these operations in code. We can't always, modify the objects from the Unity interface (for instance, when we want the player to move the object using WASD keys). Because of this, we have to apply these transformations using code.

  • Translate: transform.Translate(Vector3.forward * speed * Time.deltaTime);
  • Rotate: transform.Rotate(Vector3.up * speed * Time.deltaTime);
  • Scale: transform.localScale += scaleChange;

We can see in all 3 cases, we update the transform component of each object.

Transform Component

In order to translate or rotate an object, we call Translate or Rotate functions. Each one receives one argument: the direction in which we move/ rotate multiplied with how much we move/ rotate.

For specifying the direction we have three posibilities:

  • Vector3.forward
  • Vector3.up
  • Vector3.right

In order to compute how much we want to move/ rotate, we need to choose the speed (for innstance, 0.5f or 2.0f) and to multiply the speed with Time.deltaTime, where Time.deltaTime represents how long is a frame. Why do we need this multiplication? Well, let's say Alice and Bob play an online racing game. Let's say for Alice the game runs on 50FPS, while for Bob the game works only on 40FPS. We know now the Update() method is called 60 times per second for Alice and 40 times per second for Bob. We also know all these changes in rotation, translation and scaling should happen in Update(). As a result, for Alice, her car will move a greater distance than Bob's in a second; which is not ok. In order to make both players move the same distance in a second, we multiply the speed with how the lenght of a frame.

In order to rescale an object, we add (or subtract) from the localScale vector from transform how much we want to modify the object. localScale is a vector with 3 elements: (x, y, z).

How can an object continuously rotate?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ContinuousAnimation : MonoBehaviour
{
    public float speed;

    // Start is called before the first frame update
    void Start()
    {
        speed = 5.0f;
    }

    // Update is called once per frame
    void Update()
    {
        transform.Rotate(speed * Time.deltaTime * Vector3.up);
    }
}

How can we move an object when we press a key?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterMovement : MonoBehaviour
{
    public float speed;

    // Start is called before the first frame update
    void Start()
    {
        speed = 5.0f;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
             transform.Translate(Vector3.forward * speed * Time.deltaTime);
        }
    }
}

After we have written the script, we have to attach the script to the object. We see apply transformations on the transform component of the object. But which object? In order to match the script to an object, we do the following steps:

  1. In Scene or Hierarchy, click on the object we want to apply the script
  2. In Inspector, click on Add Component button
  3. In the search bar, write the name of the script
  4. Click on the script from the results

How to attach a script to a game object

Attach script to Game Object

Ultima modificare: Saturday, 24 July 2021, 11:29