How to Implement Movement in Different Genres of Games in Unity
In this very moving tutorial, learn how to implement movement from many different genres into your Unity games — both 2D and 3D. By Mauro Fuentes.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
How to Implement Movement in Different Genres of Games in Unity
35 mins
- Getting Started
- Different Types of Movement in Games
- Moving in 2D Versus 3D
- Understanding Transforms
- Implementing 2D Platformer Movement
- Setting Your Scene
- Adding Movement
- Customizing the Movement
- Implementing the Animator Controller
- Writing a 2D Platformer Movement Script
- Moving Catto Right and Left
- Giving Catto the Ability to Jump
- Finishing the Movement
- Adding Conditions to the Movement
- Flipping Catto
- Flipping Catto to Match His Movements
- Coding 2D Top Down Movement
- Hooking up Elements
- Writing a 2D Top Down Movement Script
- 3D Click to Rotate and Move
- Hooking up Elements
- 3D Tank Movement
- Hooking up Elements
- Writing a Tank Movement Script
- Turning Catto
- Moving Catto
- Where to Go From Here?
Moving Catto Right and Left
Now that you know what kind of movement you want Catto to have, it’s time to write the script that will implement it.
Start by dragging and dropping CattoMovement.cs to PaperCatto to add the script as a new component:
The next step is to write your script.
Double-click CattoMovement.cs so you can modify it.
The script will have three major variable groups.
The first group stores the components. Add these two lines at // 1
:
private Rigidbody2D cattoRigidbody2D;
private Animator cattoAnimator;
These two lines hold information to move and animate Catto respectively.
Here, you structure the variables to follow the “Protection, Type and Name” logic:
Notice that the simpler the variable names are, the easier it is to read them.
To use the Animator and the Rigidbody 2D, you need to tell Unity to remember them. So now, you must tell Unity what to do and where to find that information.
Add the following code so Start
looks like this:
void Start()
{
cattoRigidbody2D = GetComponent<Rigidbody2D>();
cattoAnimator = GetComponent<Animator>();
}
These two lines tell Unity: “Hey, Unity, cattoRigidbody2D
is a component of Catto, so go find it there and please remember it. Then, do the same with cattoAnimator
.”
Now, you need to keep track of Catto’s state. For example, you need to know if Catto is touching the ground or jumping.
The second group stores booleans. Add the following lines of code at // 2
:
private bool cattoIsFacingRight = true;
private bool cattoIsJumping = false;
private bool cattoIsGrounded = false;
The Boolean cattoIsFacingRight
checks if Catto is actually facing that direction. cattoIsJumping
tracks if he’s in the air, while cattoIsGrounded
tracks if he’s currently touching the ground. Both of those are false
by default.
Making the names self-explanatory saves you time, especially if you have to go back to debug your code after not working on the project for a while.
Giving Catto the Ability to Jump
This last group of variables stores the input and a special component to enable jumping. Add these six variables at // 3
:
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask ground;
public float moveInput;
public float cattoSpeed;
public float cattoJumpForce;
groundCheck
uses a groundCheckRadius
to evaluate if Catto is on the ground.
LayerMask
is a handy Unity tool to separate and order the world space into tiers. In plain English, it says: “Hey, Unity, these two objects are in the same space, so they should interact with each other.” In this case, Catto and the floor are in the same space, so they collide.
The last three variables store the float numbers that will ultimately drive Catto’s movement.
Moving on, Update
is an excellent place to poll for input, since this function is called every single frame.
Catto won’t find Ratto unless he can move so keep it up!
Finishing the Movement
There are two tasks ahead: Check if Catto is really on the ground and check the input coming from the keyboard.
Add the following lines in Update
:
cattoIsGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, ground);
moveInput = Input.GetAxis("Horizontal");
Physics2D.OverlapCircle
is a handy built-in function that informs Unity when two objects are colliding in a given area. You declared groundCheck
and groundCheckRadius
to take advantage of this function.
The variable moveInput
caches the horizontal axis of the keyboard. Pop quiz: Do you know what this value’s type is?
[spoiler title=”Solution”]
Yes! It’s a float
. Which correlates with the X-component of a Vector3.
[/spoiler]
Next, you’ll need to add four conditions to the movement logic. You’ll tackle these, one by one.
Adding Conditions to the Movement
First, add this code below the two variables you added in the last section:
// 1
if (cattoIsGrounded)
{
cattoAnimator.SetFloat("Velocity", Mathf.Abs(moveInput));
}
This value on the animator controls whether Catto looks like he’s walking — when he has a large velocity — or standing still — when his velocity is close to zero.
This translates as “If cattoIsGrounded
is true
, set the animator’s Velocity
to the value of moveInput
. Although moveInput
could be positive, it could also be negative so please use Math.Abs
so moveInput
stays positive. Thanks, C#. Bye.”
Add the second condition as follows:
//2
if (Input.GetButtonDown("Jump") && cattoIsGrounded)
{
cattoIsJumping = true;
cattoAnimator.SetTrigger("Jump");
}
This if
statement checks if the player is pressing the Jump button and if Catto is really on the ground. If so, Unity will consider it true
. If both are true, then it sets cattoIsJumping
to true
.
Finally, as before, this code says: “Hey, Unity, grab the Animator and set the trigger of Jump so Catto looks like he’s jumping.”
Here’s the third condition:
//3
if (Input.GetKeyDown(KeyCode.DownArrow) && cattoIsGrounded)
{
cattoAnimator.SetBool("Crouch", true);
}
This time, you check if the user is pressing the Down Arrow key and if cattoIsGrounded
is true
.
If so, you say: “Hey, Unity, please go to the cattoAnimator
and set the Crouch
Boolean to true
so Catto looks like he’s crouching. Thanks.”
And for the last condition:
//4
else if (Input.GetKeyUp(KeyCode.DownArrow))
{
cattoAnimator.SetBool("Crouch", false);
}
If the player has just released the Down Arrow key, go to the cattoAnimator
and set Crouch to false
. This makes Catto stand up again.
You’ve just implemented some pretty important movements: walking, jumping, crouching, and standing up again. Next, you’ll do something even fancier!
Flipping Catto
For your next step, you’ll write a custom function called FlipCatto
. Guess what it does!
Add this code:
private void FlipCatto()
{
cattoIsFacingRight = !cattoIsFacingRight;
Vector3 cattoScale = transform.localScale;
cattoScale.x *= -1;
transform.localScale = cattoScale;
}
Notice that you set cattoIsFacingRight
to its opposite value every time you call the function.
Then you store a Vector3
named cattoScale
and pass it the current scale of Catto. You multiply the cattoScale by a negative 1, which gives you the opposite image. That’s how you flip Catto over.
Finally, to work properly, the flipped image is set as the new default image until Catto flips again.
Piece of cake, right?
Flipping Catto to Match His Movements
From now on, the code goes inside FixedUpdate
because this is where Unity calculates physics.
Add this code:
cattoRigidbody2D.velocity = new Vector2(moveInput * cattoSpeed, cattoRigidbody2D.velocity.y);
Here, you set the velocity
vector of the Rigidbody 2D. To move left and right, you set the X
axis to be the moveInput
from the keyboard at the speed of cattoSpeed
, while keeping the Y
axis untouched. You’ll get to jumping in a moment.
You’re down to the last three conditions!
First, add these two if
statements below:
if (cattoIsFacingRight == false && moveInput > 0)
{
FlipCatto();
}
else if (cattoIsFacingRight == true && moveInput < 0)
{
FlipCatto();
}
In English, the first statement says: "If Catto is not facing the right direction and someone presses a key to move to the right: Flip Catto." The else if
is the opposite: "If Catto is facing right and the input points to the left: Flip Catto."
Now, for the last tweak, add this code below:
if (cattoIsJumping)
{
cattoRigidbody2D.AddForce(new Vector2(0f, cattoJumpForce));
cattoIsJumping = false;
}
This part simply uses a built-in Unity function called AddForce
. You add force specifically to the Y
axis of Catto's Rigidbody2D
. Note that you check if Catto is jumping before doing anything else.
Lastly, you set cattoIsJumping
to false. So the next time he's on the ground, he can jump.
Go back to the Hierarchy
, find CheckGround inside PaperCatto and drag and drop it through the Inspector.
Try these values:
- Ground Check Radius = 0.07
- Ground = Ground
- Catto Speed = 6.11
- Catto Jump Force = 550
One last tweak. Go to CheckGround and set it's Position to -1.18
on the Y-axis:
Finally! Press Play and marvel at such cat-ness!