Unity - Basic Movement Scripting

 Let us start with our movement script. Create a new script, and name it “Movement”.


Now, open the script

Let us create a public float variable named speed. Making a variable public in Unity has a great advantage −

  • The variable shows up as a modifiable field inside the editor, so you don’t have to manually adjust the values in code.


If we save this script without touching the other methods, it should compile in Unity.
(You can see when it is compiling by the icon in the bottom right corner.)
Next, drag and drop the script from the Assets onto the GameObject. If you do it correctly, this is what you should see in the GameObject’s properties −


Since the speed value is adjustable and need not be changed in code all the time, we can use update() method instead of start().

Let us now consider the objectives for the Update method −


    Check for the user input.

    If there is a user input, read the directions of input.

    Change the position values of the object’s transform based on its speed and direction. To do so, we will add the following code −

Let us now discuss the code in breif.

First of all, we make a floating point variable named h (for horizontal), and its value is given by the Input.GetAxisRaw method. This method returns -1, 0 or 1 depending on which key the player has pressed on the up/down/left/right arrows.

The Input class is responsible for getting input from the user in the form of key presses, mouse input, controller input, and so on. The GetAxisRaw method is slightly harder to understand, so we’ll get back to that later.

Next, we are updating the position of our gameObject to a new position defined by creating a new Vector2. The Vector2 takes 2 parameters, which are its x and y values respectively. For the x value, we provide the sum of the object’s current position and its speed, effectively adding some amount every frame the key is pressed to its position.

Save this script and head back to Unity. Unity will automatically update all scripts once it compiles successfully, so you don’t have to reattach the script again and again.

Now that you are done, change the value of the speed in the GameObject’s properties to say 0.8. This is important because a higher value will make the player move too fast.

Speed Value

Now, click Play and see your first small game in action!

Play

Try pressing the arrow keys and moving around. To stop the game, simply press Play again. You can even adjust the speed in real-time so you do not have to stop and start it all the time.

Comments