Signup/Sign In

Unity: Making the Game Object move using C# Script

So now that you know what Rigidbodies are and how to attach them, let's go ahead and put them to actual use. One of the best ways, that we can think of, to explain the working of Rigidbodies is by making the player move using the arrow keys.

To do so, open up the Movement script that we made earlier. In case you deleted it or if you're working on a clean, new project, simply create a new script and name it Movement. Open it up in your IDE, and you'll see the familiar Start() and Update() methods that we have explained earlier.

Now, let's have a look at each line of code in detail and try to understand what's going on here. Don't worry if you can't grasp all of it at once, you'll learn as we progress forward.

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

public class Movement : MonoBehaviour {

    public RigidBody2D starBody,
    public float speed;
    
    void start()
    {
        // use this function to initialize
        // anything
    }
    
    // Update is called once per frame
    void update()
    {
        starBody.velocity() = new Vector2(Input.GetAxisRaw("Horizontal")*speed, Input.GetAxisRaw("Vertical")*2);
    }

}

Line → public Rigidbody2D starBody: Simply declares an instance of the Rigidbody2D, named starBody. Make note of the public access modifier, We will be coming to that soon.

Line → public float speed: Simple declaration of a floating point value named speed. Once again, make a note of the public access modifier used here.

Line → void Start(): Note that this method is completely empty. We haven't even assigned any value to speed and starBody. You'd expect to get NullReferenceExceptions or UnassignedReferenceExceptions thrown everywhere and general chaos, if we didn't give those variables something to work with, right? And yet, this method remains mysteriously empty.

Line → ([Inside Update method] starBody.velocity = new Vector2(Input.GetAxisRaw ...): This is where the main action is going on around your game character. Let's dig into this one line, shall we? The first few words are starBody.velocity = means, we are assigning a velocity to the Rigidbody currently referenced by starBody. While new Vector2(...) means that a Rigidbody's velocity is defined as a Vector2, where the input parameters are the velocity along the X-axis and Y-axis respectively.

Now, for the actual magic in this code: Input.GetAxisRaw("Horizontal") and Input.GetAxisRaw("Vertical") What are these things? Well, the Input class is provided with MonoDevelop for handling the input. It has definitions for what you'd call Input Axes defined as Horizontal and Vertical.

What's basically going on is that the game is detecting input corresponding to the Horizontal and Vertical input axes, and setting them to -1, 0 or 1 depending on the button you press. So, when you press the Right arrow key, it means you're setting the value of the Horizontal axis to 1. As soon as you let go of that arrow key, the value on that axis jumps back to 0. Now, in game language it simply means,

move the character by 1 unit horizontally per frame when the Right arrow key is pressed.

Keeping it at 1 means the object will travel rather slowly. Hence, we multiply that value with the speed float, thus saying,

move the character by 1 times the speed, and since we know that anything times 1 is the same value, we're effectively saying move the character horizontally by this speed when the axis buttons are pressed.

NOTE: By default, the axis buttons on a standard keyboard are the Up and Down arrows, as well as W and S for the Vertical axis, and Left and Right arrows, as well as A and D for the Horizontal axis.

Moving on, what's going in that one line is basically the following sentence:

Give this rigidbody a velocity in the game world, where the horizontal velocity is (Horizontal Axis * speed) and the vertical velocity is (Vertical Axis * speed)

Now, to finish, save this script and head on back to Unity. To attach the script to an object, simply drag and drop it over that object, or go to Add Component → Scripts.

Making Player Move


Now, remember how we asked you to make note of the public access modifiers when we were writing our scripts? Have a look at the script's component.

Making Player Move


You'll notice that along with the script, Unity automatically generated 2 fields for inputting both a Rigidbody2D and a speed float. That's the magic of Unity. Values and class instances declared publically can be seen in the Editor where you can make adjustments without having to constantly have to look in your code all the time.

To set the Rigidbody2D for the first field, click on the small circle with a dot in it right next to the field. This will open up a list of available Rigidbodies in the scene which you can use. For the time being, since we only have one Rigidbody in the entire scene, click on the one that appears in the list.

Making Player Move


What did you just accomplished by doing this? Remember how we didn't assign anything to the starBody variable back when we were writing the script? This is where we assign it. We can do assigning of components and values with a simple UI instead of having to write it in the code.

Next, set a speed value in the next field. Don't set it too high, or your character might fly off before you can see where he even went. This is a problem because our Camera is stationary, so positioning it back into view will become a task much easier said, than done. We would suggest setting the speed to around 5.

This is what your script component should look like once you finish:

Making Player Move


Now click on play button and let's see what happens. If everything went right, you'll notice that you can now move your character with the arrow keys. Awesome!