Create your first game using Unity and C# – Part 2 Creating your first script to handle player movement.
Tags: gamedev, beginners, csharp, tutorial
Published: 2020-02-18 02:24:29

<a href="https://www.thedevelopingdeveloper.net/2020/02/16/create-your-first-game-using-unity-and-c-part-1-getting-your-environment-set-up-and-importing-some-art/2020-02-16_7-16-33/" rel="attachment wp-att-950"><img class="aligncenter size-medium wp-image-950 hoverZoomLink" src="https://www.thedevelopingdeveloper.net/wp-content/uploads/2020/02/2020-02-16_7-16-33-213x300.png" alt="Character with collider" width="213" height="300" /></a>
<h1></h1>
<h1>How to build a game in Unity and C# part 2 - Player Movement.</h1>
In the last tutorial we got our environment set up and worked through the process of adding a player character to our project. Now we are going to start doing some of the real work. Today we are going to learn how to build a game in Unity and C# .

In this lesson we will learn how to :
<ol>
 	<li>Add physics to our Player object</li>
 	<li>Add collision to the Player (so that he doesn't just run through walls)</li>
 	<li>Write the code that allows our player to move.</li>
 	<li>Test that our character can walk freely around our empty scene.</li>
</ol>
<h2>Lets add some physics!</h2>
In the last lesson we added a player object to our "Hierarchy" window. In this section we will add physics to our player by adding what's called "RigidBody" to our character.

<a href="https://www.thedevelopingdeveloper.net/2020/02/16/create-your-first-game-using-unity-and-c-part-1-getting-your-environment-set-up-and-importing-some-art/2020-02-16_13-08-40/" rel="attachment wp-att-985"><img class="size-medium wp-image-985 hoverZoomLink alignleft" src="https://www.thedevelopingdeveloper.net/wp-content/uploads/2020/02/2020-02-16_13-08-40-300x137.jpg" alt="Name your new object" width="300" height="137" /></a>

&nbsp;

&nbsp;

&nbsp;
<h3></h3>
<h3><strong>A</strong><strong>dd a RigidBody component to the player object</strong></h3>
<strong>Find the player in the Hierarchy and select it.</strong>

Next look to the Inspector widow, at the bottom you should see a button..

<strong>Press the "Add component" button.</strong>

Select the RigidBody2D item from the menu.

<strong>Rigidbodies</strong> enable your  <span class="tooltip"><strong>GameObjects</strong></span>  to act under the control of physics. The Rigidbody can receive forces and torque to make your objects move in a realistic way. Any GameObject must contain a Rigidbody to be influenced by gravity, act under added forces via scripting, or interact with other objects.

Make sure the player is still selected in the hierarchy window and add another component

<strong>Press the Add Component button</strong>

<strong>Add a Box Collider 2D Component  </strong>

(be sure that the component that you add is a Box Collider 2D not the other one)

Modify the collider to surround your players feet. This particular collision will be used to make sure that your character isn't able to walk through blocks or other terrain while moving around the map.

<strong>With the player selected in the Hierarchy </strong>

<strong>Select the Box Collider from the Inspector </strong>

<strong>Then hit the Edit Collider button. </strong>

A green box that surrounds your character will appear it has little squares on it which you can drag to resize your collision.

You can make this as big or as small as you want , but for right now you should make it look like mine. (Below)

&nbsp;

<img class="wp-image-950 hoverZoomLink alignleft" src="https://www.thedevelopingdeveloper.net/wp-content/uploads/2020/02/2020-02-16_7-16-33-213x300.png" alt="Character with collider" width="151" height="213" />

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;
<h2><strong>Make a script for the player movement.</strong></h2>
<h3>Add the script</h3>
<strong>Find the project Window </strong>

<strong>Select the Scripts Folder </strong>

<strong>Right click on it </strong>

<strong>Select Create from the menu and C# Script from the menu that opens </strong>

<strong>Be sure to name the Script at this time</strong>

<strong>Name it PlayerMovement.cs</strong>

<strong>Here is what it looks like initially.</strong>

<img class="size-medium wp-image-953 hoverZoomLink alignleft" src="https://www.thedevelopingdeveloper.net/wp-content/uploads/2020/02/Snag_62fa10e-300x148.png" alt="Viewing the script in the project window. " width="300" height="148" />

&nbsp;

&nbsp;

&nbsp;

&nbsp;

<strong>Double click on the script in the project window</strong>

If you followed the instructions in the last Tutorial you will have set the External Editor to Visual Studio and when you double click the new script Visual Studio will open.

You should now be looking at the project in Visual studio.

If it didn't open <a href="https://www.thedevelopingdeveloper.net/2020/02/16/create-your-first-game-using-unity-and-c-part-1-getting-your-environment-set-up-and-importing-some-art/">please refer to my last article</a> and find the section on opening your External Editor.
<h3>Modify the Script in Visual Studio</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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

    // Update is called once per frame
    void Update()
    {
        
    }
}</pre>
First change the "class name" to match the name in the unity editor (this is important the script name MUST match the class name. More on this below)

Change this line:
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">public class NewBehaviourScript : MonoBehaviour</pre>
to:
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">public class playerMovement: MonoBehaviour</pre>
In Unity  when you create a script the class name must match the script name EXACTLY. If you do not do this correctly then you will get an error which says :
<pre class="question-title EnlighterJSRAW" data-enlighter-language="raw">"Cant Add Script - "Can't add script behaviour VisualContainerAsset",
Can't Add Script "The script needs to derive from MonoBehaviour!"</pre>
**You won't see this error though until you attempt to add the script to the player model later in this tutorial.**
<h2>Let's add our script to our player!</h2>
<strong>Open Unity back up (make sure you save all the work you did in Visual Studio)</strong>

<strong>Find the Hierarchy window</strong>

<strong>Select your player from the Hierarchy</strong>

<strong>Now direct your attention to the Project view</strong>

<strong>Find your scripts folder</strong>

<strong>Select it and then select your PlayerMovement script</strong>

<strong>Drag the newly created script to the Inspector window. </strong>

If you did it correctly you will now see a new component in the inspector window named Player Movement (Script)
<h2>Coding the Player Movement</h2>
Now that we have a script we need to do a few things to handle the movement.
<ol>
 	<li>Create variables.</li>
 	<li>Set their initial values</li>
 	<li>Modify them as required for the program.</li>
 	<li>Attach the script to an object in the editor.</li>
</ol>
<h2>Let's talk about variables! - (explanation)</h2>
If you are working on this tutorial without a solid programming background. Understanding the code in a necessary part of learning to build a game in Unity and C#. You might find the use of public and private in front of the variables we are instantiating here a little confusing. Everything in this section is general knowledge about variables. If you want to just get the code thats going in the game... skip to the next section.

Without going into to much detail, let's just review a couple things about variables and how they are used in C#.
<ul>
 	<li>Variables must be "declared".
<ul>
 	<li>When you declare a variable you tell the compiler what the access level is "Public" Or "Private". Knowing how and when to use these is a whole topic in itself.
<ul>
 	<li>When it comes to Unity you can get by knowing only this much (below) about "Public / Private"
Public variables will be available to modify in the Unity inspector.. private will not.</li>
</ul>
</li>
 	<li>In general you will declare the TYPE of a variable when you instantiate it. This is what determines what kinds of values can be stored in the variable.
<ul>
 	<li>Often we think of a variable as single type like <strong><em>public int myNumber = 10; </em></strong> but you can also declare a variable to hold an entire object. An object could be much more complex than a standard variable. It could be a whole range of values. Like for instance the Player that we are creating... at some point we will probably want to give this object some properties that separate him from other objects. The properties are one of the reasons that we use classes in C#. A claa is simply an object and the object acts like a container for these properties.</li>
 	<li>Our player might have
<ul>
 	<li>a name                        public string name = "chad";</li>
 	<li>hit points                     public int hitPoints = 10000000000000000;</li>
 	<li>lives                             public int remLives = 9;</li>
</ul>
</li>
 	<li>All of the values could be contained in a "class" class Player()
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">class Player()
{

    public string name = "chad";
    public int hitPoints = 100000000000;
    public int remLives = 9;
  

}

</pre>
</li>
 	<li>Now that we have a class we can create a variable to hold the entire object. This is not a totally correct example but as long as you understand that a variable declaration can look a couple different ways you should be good to go for the rest of this .
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">public Player myPlayer = new Player();

myPlayer.name = "Chad"; 
myPlayer.hitPoints = 99999999999999999999;
myPlayer.remLives = 99999999999999999;

</pre>
</li>
</ul>
</li>
 	<li>You are able to give the variable a value when you declare it, but you do not have to.</li>
 	<li>Variables must be assigned in order to use them.</li>
</ul>
</li>
</ul>
Ok so back to the Public private thing....

More specifically what that means is , once you add a script to an object in Unity. You can add variables to that script. In creating these variables you make a choice to either declare them public or private. A public variable will have a graphical representation in the editor that you can change via the Unity inspector interface. (see below)

<img class="wp-image-957 hoverZoomLink alignleft" src="https://www.thedevelopingdeveloper.net/wp-content/uploads/2020/02/2020-02-16_9-32-15-281x300.jpg" alt="view of public properties " width="327" height="349" />

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

As you can see above. The speed variable can be increased or reduced in the GUI.

When you make a change to a public variable in the GUI, the game will apply this value at runtime every time you start the game. If you make changes to this value in the code though, that change happens after the intial start and will now be the new value. (until you restart the game)
<h2>Let's assign our variables</h2>
OK so now that we have reviewed how to use variables let's get back to building this movement script.

Assign the three variables that we are going to need.

We need a value to hold our:
<ul>
 	<li>Speed</li>
 	<li>A reference to the RigidBody that we added earlier</li>
 	<li>A value to tell Unity the change in position that we are expecting.</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">public class PlayerMovement : MonoBehaviour

{

    public float speed;

    private Rigidbody2D myRigidbody; //rigidBody gives the player physics 

    private Vector3 change; // the value we will use to tell unity where we moved 

 

    // Start is called before the first frame update

    void Start()

    {
        

    }</pre>
**note RigidBody2D is a class and has several values attached to it. **
<h3>Get a reference to the Rigidbody component that we set up earlier.</h3>
Now that we have the Rigidbody reference we need to populate it. We do this by adding a statement to the void Start() method.

Since Start() is called only once and at the beginning of an objects existence it only makes sense to do our initial setup for things in this method.

We can do this by using the built in Unity function named <strong>GetComponent&lt;Rigidbody2D&gt;();</strong>

What this is going to do is look for the component that we named between the brackets, is it exists in the object to which we attach this script. (our player)

When we attach this script to the Player object. Unity knows that it should look at the collection of components (attached to player) and find the one that matches what is between the &lt; &gt;.

In other words we are telling Unity to look at the Player, and store a reference to the component named <strong>RigidBody2D</strong> in the value myRigidbody.
<h3></h3>
<h2>Whats is happening with this change variable? - (explanation)</h2>
**In this section all of the code is for explanation purposes. You do not need to use any of this code in your script.&amp;&amp;

Next we assign our change variable. Because this is something that will be constantly changing we choose to do this in the Update() method. (In this case we are working on player movement so logically you would have the game checking for movement each frame. In other words, we are going to check for key input ,which tells the game which direction we are heading. When we get a command we will run a routine to animate the character (animation will be covered in the next article), and move them in the desired direction. This is stored in the change variable  )

If that wasn't clear.... in the update method we will:
<ul>
 	<li>set change to zero once per frame</li>
 	<li>check for movement</li>
 	<li>normalize the input (im not going into this too much just trust that we did it)</li>
 	<li>Have the character move to the new position</li>
</ul>
The change variable is just a set of values that represent changes to the players coordinates.

Something important to note here is that Vector2 is class. It contains a set of coordinates X and Y.

Unity will modify these coordinates to apply a simple movement algorithm.

You can think of this like an x and y on a graph. Moving in any direction one point results in a change in the x and y which is either positive or negative.

&nbsp;

<img class="aligncenter" style="color: #737373; font-size: 1rem;" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcR8wyvVEqGe5V6fZgtptng4CzvlxTzNOO4aPHrjAnpZQqJ9LUni" alt="Image result for x and y graph" width="421" height="360" />

As we mentioned Vectors are classes and one Vector has multiple values assigned to it . These coordinates can be changed as you see below.
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">Vector2 change;

change.X = new value

change.Y = new value</pre>
You do not have to change both values but each change represents movement on the graph.

In our code (which is below in full)  we are going to use some Unity libraries to get input in the form of keys pressed from the player. We will then covert that to our change variable. Don't think about this too hard right now, it just works. But later were going to use that movement along with another Unity function called MovePosition().

MovePostion() will take that change value that we stored and a couple other values to figure out where the player is moving and how fast.
(WASD  or the arrow keys are tracked within unity and are converted to movement (change data))
<h2>Make the changes to the change variable</h2>
(This section might be hard to understand because there is a lot going on here and Unity is handling a lot of things for us with built in functions.

I will do my best to explain what is happening here, if you don't fully understand it you can always come back later and play around with it until you do.)

Now were going to tell Unity to make changes when the player moves.

We're also going to add a Debug statement to the log so we can view the changes that occur due to movement in the Unity Console.

Here is what our code looks like at this point.
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">using System.Collections;

using System.Collections.Generic;

using UnityEngine;

 

public class PlayerMovement: MonoBehaviour

{

    public float speed;

    private Rigidbody myRigidbody; //rigidBody gives the player physics 

    private Vector2 change; // the value we will use to tell unity where we moved 

    
    // Start is called before the first frame update

    void Start()

    {

        myRigidbody = GetComponent&lt;Rigidbody&gt;(); //add the rigidbody component to this script for use later. 

    }

 

    // Update is called once per frame

    void Update()

    {

        //Zero out the change

        change = Vector2.zero;
        

        //Get the current x and y as points on a graph

        change.x = Input.GetAxisRaw("Horizontal");

        change.y = Input.GetAxisRaw("Vertical");

        //print the change to the console 

        Debug.Log(change);
 

    }

}
</pre>
<strong>Input the code and then save your work  in Visual Studio. </strong>

<strong>Go back to the Unity Editor</strong>

<strong>Select your player by either clicking on the sprite or selecting the node named "Player" in the Hierarchy tab of Unity.</strong>
<h2>Let's talk about the code that makes the player move..(explanation of functions/ methods)</h2>
OK guys we are almost done with this lesson but before we finish up let's talk about what we are about to do and then let's get it done and tested!

In the next section we are going to write our first "method". Methods , functions, sub routines.. these are all terms that get thrown around in programming but they are all basically the same thing.
A method is a bit of code that you can call from somewhere in your program. When it is called, the code inside the method will be processed. When the code inside the method is finished executing, the program will resume execution where the method was called. The next line of code after the method was called will then execute.

&nbsp;
<h3>When should I create a new method?</h3>
Often as a software engineer you will be faced with the question of... "When should I create a new method?"

The simple answer is: When you encounter a verb.

Let's break that down a bit!
In our program we are going to create a method called MoveCharacter(). We could just add the movement code to the Update() method but then later in our program we might need to write the exact same code again (if we need to move again).

When it comes to deciding on when to create a new method you can can think of them as verbs. "Brad wants to run", "Brad attacks".... In both of these sentences, if we are writing code to make our player do some action it makes sense to create a method for both verbs.

Let's take this one step farther now.

Let's say that we want to write this code to handle PlayerMovement or "Move" (Player) if we are keeping with the Verb reference.

Each time we get a frameUpdate, we want to evaluate if the user pressed a button to tell the computer to Move() (our verb!).
What might happen in the Move() method then?
Well as we discussed earlier, when we move, we need change our players X and Y position.
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">void MoveCharacter()
{

     player.MovePostion(currentPostion +change) 

}</pre>
So when we Move(), we are actually telling the computer to move our player, some amount of degrees X, and move our player some amount of degrees Y. (There are those dang verbs again!)
We can boil that down to MoveX and MoveY. (TWO Verbs!)

If we look back at the psuedocode above, what do we see ? We have a method that Moves the character a,nd inside of it we have ANOTHER method call, which handles our MoveX and MoveY.

Why is there another method there? Because we encountered another verb. (MoveX and MoveY)

I can't say that this is a hard and fast rule because when it comes to programming, there will always be exceptions to every rule. But if you can take that simple statement with you then you have a good baseline to answer the question.

"When should I create a new method?"

Hope that helps this next part make a little more sense for you!
<h2>Writing the movement code.</h2>
OK so here it is.. all of the code we need for (now anyway) our player movement.
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed;
    private Rigidbody2D myRigidbody; //rigidBody gives the player physics 
    private Vector3 change; // the value we will use to tell unity where we moved 


    // Start is called before the first frame update
    void Start()
    {
        myRigidbody = GetComponent&lt;Rigidbody2D&gt;(); //add the rigidbody component to this script for use later. 
    }

    // Update is called once per frame
    void Update()
    {
       
        //Zero out the change
        change = Vector3.zero;
         //Get the current x and y as points on a graph
        change.x = Input.GetAxisRaw("Horizontal");
        change.y = Input.GetAxisRaw("Vertical");
        //print the change to the console 
        Debug.Log(change);
        if (change != Vector3.zero)
        {
            MoveCharacter();
        }

    }
    void MoveCharacter()
    {
        //transform.position is the player position
        // add the "change" (x and y modifications) 
        //Time.Delta is the amount of time that has passed since the previous frame 
        //So what we are saying here is: Move my character TO my current poistion + the changes I asked to make (direction) * my current speed * the amount of time that has passed.
        //this last piece about the time change is to make it look more smooth when your character moves. 
        myRigidbody.MovePosition(transform.position + change * speed * Time.deltaTime);
    }

}</pre>
<h3>Breaking the code down</h3>
Each frame  (the update() method)
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">void Update()
    {
       
        //Zero out the change
        change = Vector3.zero;
         //Get the current x and y as points on a graph
        change.x = Input.GetAxisRaw("Horizontal");
        change.y = Input.GetAxisRaw("Vertical");
        //print the change to the console 
        Debug.Log(change);
        if (change != Vector3.zero)
        {
            MoveCharacter();
        }
</pre>
Let's get our change x and change y and store it as our change variable.
<pre>change = Vector3.zero;
         //Get the current x and y as points on a graph
        change.x = Input.GetAxisRaw("Horizontal");
        change.y = Input.GetAxisRaw("Vertical");</pre>
log to the console the change values
<pre>Debug.Log(change);
</pre>
and IF our change value is not 0 (<a href="https://www.thedevelopingdeveloper.net/2020/02/14/understanding-the-c-if-statement/">you can read up on if statements an expressions here</a> )
<pre>if (change != Vector3.zero)
       {
           MoveCharacter();
       }</pre>
THEN MoveCharacter()

Within the Move character we use a unity function to Move an object to the given position.

There is some other math happening here but I'm not going to go into that today.
<pre>void MoveCharacter()
  {
      //transform.position is the player position
      // add the "change" (x and y modifications) 
      //Time.Delta is the amount of time that has passed since the previous frame 
      //So what we are saying here is: Move my character TO my current poistion + the changes I asked to make (direction) * my current speed * the amount of time that has passed.
      //this last piece about the time change is to make it look more smooth when your character moves. 
      myRigidbody.MovePosition(transform.position + change * speed * Time.deltaTime);
  }
</pre>
&nbsp;
<h2>Finally! We are done and we can test.</h2>
Go back to the unity editor.

Hit play!

<a href="https://www.thedevelopingdeveloper.net/2020/02/17/build-a-game-in-unity-and-c-create-your-first-game-learn-net-by-building-a-2d-game/2020-02-17_16-11-20/" rel="attachment wp-att-1008"><img class="size-medium wp-image-1008 hoverZoomLink alignleft" src="https://www.thedevelopingdeveloper.net/wp-content/uploads/2020/02/2020-02-17_16-11-20-300x215.jpg" alt="Hit the play button" width="300" height="215" /></a>

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

Your scene should start and now you should be able to see the first fruits of your labor.

Try using the arrows keys or the WASD keys to move around. Your player should move around the screen!
<h3>One last thing for fun!</h3>
OK stop your game by pressing the Play button again.

<strong>Now go to your Hierarchy view </strong>

<strong>Select your player from the hierarchy window. (Or click on him in the scene)</strong>

Look over to the inspector and find the Player Movement (Script) component.

As I mentioned earlier , because we made the speed variable public we can modify it in this view.

Just for fun change it to 44. Hit play again and now try to move.

If everything is working properly then you should run "a bit" faster than you did earlier.

I hope you had fun learning how to build a game in Unity and C#

If you like this series and want to see more <a href="https://www.thedevelopingdeveloper.net/">head on over to my blog </a>and sign up for my mailing list of leave me a comment.
<div id="hzImg" style="border: 1px solid #ffffff; line-height: 0; overflow: hidden; padding: 2px; margin: 0px; position: absolute; z-index: 2147483647; border-radius: 3px; box-shadow: rgba(0, 0, 0, 0.33) 3px 3px 9px 5px; opacity: 1; top: 3067px; left: 224px; background-color: #ffffff; cursor: pointer; pointer-events: none; display: none;"></div>
<div id="hzImg" style="border: 1px solid #ffffff; line-height: 0; overflow: hidden; padding: 2px; margin: 0px; position: absolute; z-index: 2147483647; border-radius: 3px; box-shadow: rgba(0, 0, 0, 0.33) 3px 3px 9px 5px; opacity: 1; top: 3586px; left: 23px; background-color: #ffffff; cursor: pointer; pointer-events: none; display: none;"></div>
<div id="hzImg" style="border: 1px solid #ffffff; line-height: 0; overflow: hidden; padding: 2px; margin: 0px; position: absolute; z-index: 2147483647; border-radius: 3px; box-shadow: rgba(0, 0, 0, 0.33) 3px 3px 9px 5px; opacity: 1; top: 11021px; left: -6px; background-color: #ffffff; cursor: pointer; pointer-events: none; display: none;"></div>
<img id="hzDownscaled" style="position: absolute; top: -10000px;" />
<div id="hzImg" style="border: 1px solid #ffffff; line-height: 0; overflow: hidden; padding: 2px; margin: 0px; position: absolute; z-index: 2147483647; border-radius: 3px; box-shadow: rgba(0, 0, 0, 0.33) 3px 3px 9px 5px; opacity: 1; top: 643px; left: 319px; background-color: #ffffff; display: none;"></div>
<div id="hzImg" style="border: 1px solid #ffffff; line-height: 0; overflow: hidden; padding: 2px; margin: 0px; position: absolute; z-index: 2147483647; border-radius: 3px; box-shadow: rgba(0, 0, 0, 0.33) 3px 3px 9px 5px; opacity: 1; top: 5256px; left: 92px; background-color: #ffffff; cursor: pointer; pointer-events: none; display: none;"></div>
<div id="hzImg" style="border: 1px solid #ffffff; line-height: 0; overflow: hidden; padding: 2px; margin: 0px; position: absolute; z-index: 2147483647; border-radius: 3px; box-shadow: rgba(0, 0, 0, 0.33) 3px 3px 9px 5px; opacity: 1; top: 0px; left: 61px; background-color: #ffffff; cursor: pointer; pointer-events: none; display: none;"></div>