Implement object collisions for your 2D game
Tutorial
·
Beginner
·
+10XP
·
30 mins
·
(1431)
Unity Technologies

In this tutorial, you’ll configure your player character and decorations so they collide.
By the end of the tutorial, you’ll be able to do the following:
- Implement collisions in your game using Rigidbody and Collider components.
- Troubleshoot game errors related to the physics system.
Languages available:
1. Overview
Now that you’ve created an environment for the game world that the player character will explore, you can start to set up different ways for the player to interact with that world. The first aspect of this is making the world feel a little more realistic by implementing some basic laws of physics in your game.
Physics in games refers to the properties of objects and how they respond to forces. Some games aim to simulate physics in a way that replicates the real world — for example, a game with the goal of replicating the experience of driving a racing car as accurately as possible. Other projects take a more flexible approach and implement rules of physics that deviate from the real world, such as unexpected behavior when objects collide or impossible leaps that the player character can make.
By the end of this tutorial, you’ll be able to do the following:
- Implement collisions in your game using Rigidbody and Collider components.
- Troubleshoot game errors related to the physics system.
Working on your own project?
This tutorial is part of Beginner 2D: Adventure Game and refers to the game project for that course, but this information will be helpful for any beginner creator who wants to set up basic physics in their 2D game.
Note: For the purposes of this tutorial, we chose to use the Ruby’s Adventure asset set, and the file paths used in instructions will reflect this. If you chose another asset set, the file names will be the same, but in your corresponding theme folder.
2. Add a rigidbody component to the player character prefab
To simulate physics in your Unity project, use the built-in 2D Unity physics system. Just as Unity is a framework for creating games, the 2D physics engine is a framework that integrates into the game engine so you can implement the laws of physics, such as gravity, into your project. Unity only does physics calculations for GameObjects that have Rigidbody components attached to avoid doing resource-intensive calculations when they’re not actually needed.
To make the player character GameObject a prefab and add a Rigidbody component, follow these instructions:
1. Turn the PlayerCharacter GameObject into a prefab.
2. Open the PlayerCharacter prefab in prefab editing mode.

3. In the Inspector window, select Add Component.
4. Search for “Rigidbody 2D” and select this component.

Important: You must select the 2D version of this component because your game is 2D.
5. In the prefab editing mode toolbar at the top of the Scene view, make sure that Auto-save is enabled.
6. To exit prefab editing mode, select Scenes in the breadcrumbs in the upper-left corner of the window, or select the arrow to the left side of the PlayerCharacter prefab.

7. Select Play to enter Play mode and test your changes.
Oops, your character just slid down the screen and out of view — that needs to be fixed!
Why does the player character fall off the screen?
The character slid down the screen because the Rigidbody 2D component is applying gravity to the GameObject. By default, gravity pulls a GameObject down the y-axis, so the GameObject was pulled down beyond the camera view of your scene. This default configuration won’t work for your game: your game has a top down view, which means everything is the ground, not just the bottom of the player’s screen.
3. Disable gravity for the player character
To disable gravity for the PlayerCharacter GameObject, follow these instructions:
1. In the Hierarchy window, select the PlayerCharacter GameObject.
2. In the Inspector window, under the Rigidbody 2D component, set the Gravity Scale property to 0.

3. Save your changes.
Notice that a vertical blue line is now present next to the Gravity Scale property — this is because you have made changes to the prefab instance for the PlayerCharacter GameObject rather than the prefab asset itself.

This difference between an instance and the prefab asset is called an override, because changes to instances will always take precedence over the default configuration of the prefab asset. In this situation, you will never want the character to fall off the player’s screen, so you actually need to apply the override to the prefab asset itself.
4. In the GameObject header at the top of the Inspector window, select the Overrides dropdown. The dropdown menu displays the Rigidbody 2D component you just made a change to.

5. Select Apply All.
6. Test your changes in Play mode — the character will now move as expected without falling off the screen.
4. Add a collider to the player character prefab
Rigidbody components tell the physics system that the PlayerCharacter GameObject will interact with the forces of physics. Now you also need to add a component to tell the physics system that the GameObject is solid: a collider.
Colliders have simple shapes like squares and circles that represent the approximate shape of a GameObject. The physics system uses this approximate shape to complete its physics calculations related to the GameObject the collider is attached to.
To add a collider to your player character, follow these instructions:
1. Open the PlayerCharacter GameObject in prefab editing mode.

2. In the Inspector window, select Add Component.
3. Search for “Box Collider 2D” and select this component. All the player character sprites for the 2D Beginner course are roughly rectangular, so this collider is a good fit. The Scene view will now show your PlayerCharacter GameObject sprite surrounded by a green box.

The box is the shape of the collider and the shape of the player character for the physics system.
4. In the Inspector window, select Edit Collider.

The collider currently contains the entire sprite for the character, but with the top down perspective of this game, that could result in the character’s movement not feeling right for a player. For example, the character won’t be able to walk directly in front of an object in the scene with the current collider size — the character’s head wouldn’t cover the object at all.
5. In the Scene view, resize the collider in the following ways:
- Make the collider’s width fit the bottom of the player character sprite.
- Make the collider’s height cover the lower part of the sprite.

You can adjust the exact collider sizing after you’ve completed the rest of this tutorial and tested the game, if you want to.
6. Exit prefab editing mode.

5. Configure an object to collide with the player character
You’ve configured the player character to collide with objects, but at the moment there’s nothing for it to collide with in your game. However, in the previous tutorial you added decorative objects to the game — these will be perfect to test collision.
To configure the decorative GameObject, follow these high-level instructions:
1. Choose one of the decorative objects that you set up and open the prefab asset in prefab editing mode.
2. Add a Box Collider 2D component to the prefab.
Important: This decoration doesn’t need a Rigidbody component because the forces of physics don’t need to affect it. The decoration does need a collider component so that GameObjects with Rigidbody components can interact with it correctly.
3. Adjust the collider size to cover the following:
- The full width of the decoration sprite.
- Half the height of the sprite.
4. Save your changes.
5. Enter Play mode and test the game — try to get the player character to move around and through the decoration GameObject. You should notice that although the player character can’t move through the decoration, the player character does jitter and rotate when you try to move around the decoration.
6. Fix the player character rotation
The PlayerCharacter GameObject is currently rotating when you try to move it around the decoration because the physics system is attempting to simulate real world physics. In a 2D game, this approach doesn’t work.
To configure the player character to stop this rotation happening, follow these instruction:
1. Open the PlayerCharacter prefab.
2. In the Inspector window, find the Rigidbody2D component.
3. Select the Constraints section foldout to reveal its properties.

4. Enable Freeze Rotation to stop the Rigidbody component applying rotation to the player character.

5. Save your changes then exit prefab editing mode.
7. What is causing the jittering?
Now you need to address the remaining issue: the player character jittering.
How does the physics system calculate and apply physics forces?
Jittering happens because the physics system uses a simplified copy of the scene that only contains the colliders. This approach makes calculations simpler for the system, but it also means that whenever a GameObject with a Rigidbody component moves in the scene, the system needs to perform the following actions:
- Move its copy of the GameObject in the simplified physics scene.
- Apply forces and compute any collisions.
- Move the GameObject in your scene to the new position calculated in the physics scene, which may be affected by the calculations that the system has completed.
What exactly is causing the jittering?
When you tested movement around the decoration GameObject with colliders attached, the following things happened:
- You moved the character during the frame update.
- The physics system moved its copy of the PlayerCharacter GameObject to that new position.
- The system found that the PlayerCharacter GameObject’s collider was now inside the collider for the FirstDecoration GameObject.
- The system moved its copy of the PlayerCharacter GameObject back outside the collider for the FirstDecoration GameObject.
- The system synchronized the PlayerCharacter GameObject in your scene with that new position.
When you were testing, you were constantly moving the PlayerCharacter GameObject inside the decoration’s collider and the physics system was moving it back out again. The conflict between the player input and the physics system’s standard behavior causes the jittering.
How am I going to fix the issue?
You need to move the PlayerCharacter GameObject using its Rigidbody component rather than its Transform values. This approach to movement makes it easier for the physics system to synchronize the GameObject position to the Rigidbody position: the physics system can stop the movement before the PlayerCharacter GameObject gets inside the decoration’s collider, rather than having to move the player character out after it is already inside the collider.
Physics computation needs to update at regular intervals to be stable. At the moment, you’re performing calculations in the Update function, which is called every time a new image is rendered (the fps rate). The Update call rate can vary dramatically — it could be 20 times per second on a slow computer or 300 times on a fast one.
Unity has an alternative function for physics calculations: FixedUpdate is called at regular intervals and has the same frequency as the physics system, so you’re going to move your physics calculations to this new function. However, you shouldn’t read input data in this function, because you could miss user input due to the fixed rate of updates. To avoid this issue, you’re going to keep the instruction that reads Move Action values in the Update function.
8. Fix the PlayerCharacter jittering
To modify your approach to player movement, follow these instructions:
1. Open the PlayerController script in your IDE.
2. Add the following instruction at the beginning of the PlayerController class, after the MoveAction declaration:
Rigidbody2D rigidbody2d;
This instruction declares a new variable called rigidbody2d. This variable needs to be accessed within this script but not in Unity Editor, so the declaration does not include the public keyword.
3. Add another instruction immediately below to declare the Vector2 variable move:
Vector2 move;
4. In the Start function, beneath the instruction enabling the MoveAction, add the following instruction:
rigidbody2d = GetComponent<Rigidbody2D>();
This instruction gets the reference for the Rigidbody component attached to the GameObject that this script is attached to — the PlayerCharacter GameObject. All GameObjects have Transform components by default, so Unity makes a variable for the Transform component available in scripts by default too. You need to add a Rigidbody component when you want to use it, so you also need to specifically get the component reference.
4. In the Update function, remove the physics calculation instructions and the Vector2 type for the move variable (because you declared this already at the beginning of the class). The Update function should now look like this:
void Update()
{
move = MoveAction.ReadValue<Vector2>();
Debug.Log(move);
}
5. Underneath the Update function, declare the FixedUpdate function:
void FixedUpdate()
{
}
You’ll learn more about the details of creating a new function in a later unit of this course.
6. In the FixedUpdate function, add the following updated instruction that contains the calculation to use the rigidbody2d variable’s position values rather than the Transform component’s values:
Vector2 position = (Vector2)rigidbody2d.position + move * 3.0f * Time.deltaTime;
rigidbody2d.MovePosition(position);
This approach to setting the player character’s position moves the character based on the user’s input, but will stop that movement if the player character hits a GameObject that also has a collider. If you want to know more about this behavior, start with the Unity Scripting API documentation for MovePosition.
7. Save your changes and test the game in the Unity Editor. The jittering issue should now be resolved.
9. More things to try
If you want to further develop your skills, explore new concepts, or improve your project, check out some of the optional activities below. Each one is tagged as either Easy, Medium, or Difficult, so you can choose the level of challenge.
These activities are entirely optional, so if you’re not interested, no problem — just skip this step. We do recommend attempting at least one of them in order to get the most out of this learning experience. Good luck!
Easy: Add colliders to other decorations
Now you’ve got experience configuring colliders, set them up for any other decoration prefabs that you’ve set up that the player character shouldn’t be able to walk through. For example, small plants and flowers don’t need colliders, but a building or similarly large decoration definitely needs a collider!
Medium: Design a gauntlet for the player character
In your game, there are going to be two things that deal damage to the player character: static damage zones and patrolling enemy characters. Think about how you can adjust your game design so that the player has to engage with these obstacles before they can reach part of the environment.
If you like your idea, try it out in Unity!
10. Check your script
If you’re completing the 2D Beginner course, take a moment to check that your script is correct before continuing.
PlayerController.cs
Important: If you completed any extension work in your script, this will not be reflected in the reference script below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
// Variables related to player character movement
public InputAction MoveAction;
Rigidbody2D rigidbody2d;
Vector2 move;
// Start is called before the first frame update
void Start()
{
MoveAction.Enable();
rigidbody2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
move = MoveAction.ReadValue<Vector2>();
Debug.Log(move);
}
void FixedUpdate()
{
Vector2 position = (Vector2)rigidbody2d.position + move * 3.0f * Time.deltaTime;
rigidbody2d.MovePosition(position);
}
}
11. Next steps
You’ve started the work of integrating physics in your game world, but there’s still some more to do. In the next tutorial, you’ll set up tilemap collision so the player character can no longer walk on water tiles, which will make your game feel more realistic and help you to craft a more nuanced environment design.