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?
Coding 2D Top Down Movement
Top down movement is when the user perceives one of the axes of movement as planar. That is, you perceive Catto going to the background when you press Up. Compare that with PaperCatto, which jumps on the spot when you press Up instead.
Published games in this genre include: Bomberman, Golden Axe Warrior, The Legend of Zelda, BattleShip and HALO Spartan Assault.
Hooking up Elements
Open the scene in RW/2D TopDown Movement/Scenes.
Now, in the Hierarchy, select Player Objects ▸ Catto ▸ Catto, the one with the Sprite Renderer.
Add the following components in the Inspector:
- A Rigidbody 2D
- A Box Collider 2D
- An Animator
Here's a challenge for you: Try adding these elements on your own. If you have any trouble, follow this aid:
The Animator won't work without an Animator Controller. So, go to 2D TopDown Movement/Models/Catto and find the CattoAnimator controller. Drag and drop it into the Animator in the Inspector:
Press Play and... Catto falls down. You need to adjust the Rigidbody 2D to fix that. Gravity's causing Catto to fall so set the Gravity Scale property to 0
and try again.
Excellent! Catto stays put. He looks like he's actually on the floor from this perspective. He still can't move, though.
Writing a 2D Top Down Movement Script
Go to 2D TopDown Movement/Scripts and drag and drop TopDownMovement.cs into Catto. You can also do this:
Perfect! Double-click the script in the Inspector to edit it. This script seems much simpler than the previous one.
Now, add these three variables:
public int velocity;
private Vector3 movement;
private Animator cattoAnimator;
In Start
, you tell Unity what to do with cattoAnimator. Use GetComponent
so Unity associates the name cattoAnimator
with the Animator attached to the GameObject.
Add this code:
cattoAnimator = GetComponent<Animator>();
As you did before, use Update
to get input from the keyboard. Add this code:
movement = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
cattoAnimator.SetFloat("Horizontal", movement.x);
cattoAnimator.SetFloat("Vertical", movement.y);
cattoAnimator.SetFloat("Amount", movement.magnitude);
transform.position = transform.position + movement * velocity * Time.deltaTime;
Breaking that up:
The variable movement
contains the information from the horizontal and vertical axes from the keyboard.
It would go something like this:
The three calls to cattoAnimator
use SetFloat
, a built-in Unity function. Basically, it translates as: "Hey, Unity, look for Horizontal
in cattoAnimator
. Once you have it, pass the value of movement
to it."
In this case, movement.x
is just the X
axis component. That is to say:
What about the last call? What's magnitude?
Magnitude is the result you get from two vectors fighting each other. As you need a diagonal movement, C# calculates magnitude
for you.
Almost there... Don't forget to set the Velocity in the Inspector. 3
is a good value to start with.
Press Play and...
Done! But wait, there's more.
Go to 2D TopDown Movement/Scripts and add CollectCoins.cs to Catto. Now you can actually play the game.
Excellent! You finished the movement for your 2D top down game.
3D Click to Rotate and Move
Welcome to 3D worlds! From now on, all the games you'll cover are in 3D space.
Click to rotate and move games use the Diablo type of movement, where you click something to get contextual information and/or to move to a specific place.
Other examples of published games in this genre include: League of Legends, Age of Empires, Grim Fandango and Monkey Island.
Hooking up Elements
Open the scene in 3D ClickToRotate Movement/Scene.
So, by now you know what to do: You need to hook everything up first. Add the following components to Catto:
Adding a NavMesh Agent
Writing a Click to Rotate and Move Script
This is how to do it:
You also need to edit the Collider's size. Tip: switch to 2D view to help with sizing.
Expand Rigidbody in the Inspector. Go to Constraints, then freeze the rotation in X
, Y
and Z
by checking the boxes.
To hook up the CattoAnimator, expand Animator in the Inpector. Go to 3D ClickToRotate Movement/Models/Catto/Animator and drag and drop it into the Controller.
You can do the same for the Avatar, or you can just hook it up in the Inspector:
Finally, make sure to check Apply Root Motion.
Here's how the final result looks:
Press Play. Catto will show the default idle animation, although he can't move yet.
So now you've set Catto up for animations. Next, you'll get him moving!
There's a special module Catto needs called a NavMesh: Nav for navigation, Mesh for... er... mesh :V. Seriously, it is a mesh: A very primitive shape that stores information about distance, position and other simple calculations.
The Agent is a program that performs certain tasks for you automatically.
A NavMesh Agent needs a NavMesh to work.
Look for Nav Mesh Agent in the Inspector and add it to Catto. The following settings work fine:
Feel free to experiment though, especially with the steering.
Open ClickToMove.cs in 3D ClickToRotate Movement/Scripts.
Add the following line to the top of the file:
- A Box Collider
- A Rigidbody
- An Animator
This is how to do it:
You also need to edit the Collider's size. Tip: switch to 2D view to help with sizing.
Expand Rigidbody in the Inspector. Go to Constraints, then freeze the rotation in X
, Y
and Z
by checking the boxes.
To hook up the CattoAnimator, expand Animator in the Inpector. Go to 3D ClickToRotate Movement/Models/Catto/Animator and drag and drop it into the Controller.
You can do the same for the Avatar, or you can just hook it up in the Inspector:
Finally, make sure to check Apply Root Motion.
Here's how the final result looks:
Press Play. Catto will show the default idle animation, although he can't move yet.
So now you've set Catto up for animations. Next, you'll get him moving!
Adding a NavMesh Agent
There's a special module Catto needs called a NavMesh: Nav for navigation, Mesh for... er... mesh :V. Seriously, it is a mesh: A very primitive shape that stores information about distance, position and other simple calculations.
The Agent is a program that performs certain tasks for you automatically.
A NavMesh Agent needs a NavMesh to work.
Look for Nav Mesh Agent in the Inspector and add it to Catto. The following settings work fine:
Feel free to experiment though, especially with the steering.
Writing a Click to Rotate and Move Script
Open ClickToMove.cs in 3D ClickToRotate Movement/Scripts.
Add the following line to the top of the file:
You also need to edit the Collider's size. Tip: switch to 2D view to help with sizing.
using UnityEngine.AI;
This gives you access to NavMeshAgent
.
Then add these three variables at the top of the class:
public Animator cattoAnimator;
public NavMeshAgent cattoNavigation;
private Transform targetDestination;
This time, you're writing a NavMeshAgent
variable type. But you already know how this works.
As you did previously, you initialize variables in Start
:
void Start()
{
cattoNavigation = GetComponent<NavMeshAgent>();
cattoAnimator = GetComponent<Animator>();
}
There's a must-have function for click and move games: Physics.Raycast
.
Add this code in Update
:
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
{
cattoNavigation.destination = hit.point;
cattoAnimator.SetBool("Walking", true);
}
}
if(cattoNavigation.remainingDistance <= cattoNavigation.stoppingDistance)
{
cattoAnimator.SetBool("Walking", false);
}
What's happening here? When the player presses the left mouse button, the current position of the mouse on screen (a 2D coordinate) is converted into a ray with ScreenPointToRay
. The ray is then cast into the 3D scene with Physics.Raycast
, a technique known as hit testing. The out
keyword specifies that the hit results should be stored in the provided hit
parameter.
Finally, you set cattoNavigation.destination
to hit.point
once the ray-cast hits something, which should be where the mouse was clicked in 3D space.
The call to the cattoAnimator
, as you saw before, asks for the Walking
animation.
In plain English, "Hey, Unity, shoot a ray where I clicked and set Catto's destination to the place on the ground where that ray hits."
The last if
compares the distance between the two points: where you clicked and where Catto should stop moving. You can change this value in the Inspector.
Add the script ClickToMoveto Catto and run your game. Follow the path to find Ratto!
Congrats! You've learned how to move a character in three different game types. Just one more to go.