Unity Game Engine · High School Game Programming

Lesson 9: Collision Playground

Difficulty: Easy45–60 MinutesCollider2DRigidbody2DCollision Detection

Lesson Overview

In this lesson, you will create a Collision Playground using the Unity game engine. Build a simple 2D environment containing walls, obstacles, and a player that can move around the scene. Learn how Unity's physics engine detects collisions and keeps objects from passing through solid surfaces. You will also write C# scripts that identify collisions and triggers.

End product: A working top-down 2D playground in which the player moves using the keyboard, bumps into solid walls and obstacles, and generates messages when touching or overlapping objects.

1. Learning Objectives

  1. Explain collision detection in 2D games.
  2. Add Collider2D components to GameObjects.
  3. Explain the difference between Rigidbody2D and Collider2D.
  4. Create walls and obstacles that block player movement.
  5. Write C# code that detects collisions.
  6. Use the Unity Console to display collision messages.
  7. Test and troubleshoot collision behavior.

2. Key Vocabulary

TermDefinition
Collider2DDefines a 2D object's collision boundary.
Rigidbody2DEnables an object to participate in Unity's 2D physics simulation.
Collision DetectionDetermines when two objects touch or overlap.
Box Collider 2DRectangular collision boundary.
Circle Collider 2DCircular collision boundary.
TriggerA collider that detects overlaps without physically blocking objects.
OnCollisionEnter2D()A method called when a qualifying physical collision contact begins.
OnTriggerEnter2D()A method called when a qualifying trigger overlap begins.

3. Materials Needed

4. Step-by-Step Instructions

Step 1 — Open or create a Unity project

  1. Open Unity Hub.
  2. Open your previous 2D project, or create one called Lesson9_CollisionPlayground.
  3. Open the Scene view.
  4. Save the scene as CollisionPlayground.

Step 2 — Create the player

  1. In the Hierarchy, right-click and select 2D Object → Sprites → Square (wording may differ by Unity version).
  2. Rename the object Player.
  3. Set Position to X = 0, Y = 0, Z = 0.
  4. Set Scale to X = 0.7, Y = 0.7, Z = 1.
  5. Change its color to blue.
  6. Add Rigidbody 2D and Box Collider 2D components.
Rigidbody2D SettingValue
Body TypeDynamic
Gravity Scale0
Linear Damping0
Freeze Rotation ZEnabled
Collision DetectionContinuous
Why Gravity Scale = 0? This is a top-down environment: the player should move up, down, left, and right without falling toward the bottom of the screen.

Step 3 — Create four walls

  1. Create another Square sprite and rename it WallTop.
  2. Set its Position to (0, 4, 0) and Scale to (10, 0.5, 1).
  3. Change its color to gray and add a Box Collider 2D.
  4. Duplicate the wall to create the other three boundaries using the table below.
WallPosition XPosition YScale XScale Y
WallTop04100.5
WallBottom0-4100.5
WallLeft-500.58
WallRight500.58

Do not add Rigidbody2D to the stationary walls; their Box Collider 2D components act as solid obstacles. Ensure Is Trigger is unchecked.

Step 4 — Add three obstacles

Create three square sprites and add a Box Collider 2D to each one.

ObjectPosition (X, Y, Z)Scale (X, Y, Z)Color
Obstacle1(-2, 1, 0)(1, 1, 1)Red
Obstacle2(2, -1, 0)(1, 2, 1)Orange
Obstacle3(0, 2, 0)(2, 0.5, 1)Purple
WallTopWallBottomObstacle 1Obstacle 2Obstacle 3Player
Example layout: gray boundaries, three obstacles, and a blue player. Not to scale.

Step 5 — Program player movement

Create a C# script named PlayerCollisionMovement and attach it to Player.

using UnityEngine;

public class PlayerCollisionMovement : MonoBehaviour
{
    public float moveSpeed = 5f;

    private Rigidbody2D rb;
    private Vector2 movement;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");

        movement = new Vector2(moveX, moveY).normalized;
    }

    void FixedUpdate()
    {
        rb.linearVelocity = movement * moveSpeed;
    }
}

Code explanation: moveSpeed controls speed; Input.GetAxisRaw() reads keyboard controls; .normalized avoids faster diagonal movement; FixedUpdate() runs on the physics update schedule; and rb.linearVelocity sets the player's velocity.

Unity version note: This script uses Unity 6's linearVelocity property. In Unity 2022/2023, replace it with velocity. For Unity 6, enable the legacy Input Manager or Both under Edit → Project Settings → Player → Active Input Handling so Input.GetAxisRaw() works.

Step 6 — Test collisions

  1. Save your script and return to Unity.
  2. Press Play and click inside the Game view.
  3. Use W/A/S/D or arrow keys to move.
  4. Move into each boundary and obstacle.
Expected result: The player moves in open space but stops or slides along solid walls and obstacles, rather than passing through them.

Step 7 — Detect collisions with C#

Create a second C# script named CollisionDetector and attach it to Player.

using UnityEngine;

public class CollisionDetector : MonoBehaviour
{
    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Player collided with: "
                  + collision.gameObject.name);
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        Debug.Log("Player stopped touching: "
                  + collision.gameObject.name);
    }
}

Open Window → General → Console, press Play, and bump into obstacles. You should see messages similar to these:

Player collided with: WallTop
Player stopped touching: WallTop
Player collided with: Obstacle1

Remember: OnCollisionEnter2D() runs when physical contact begins; it does not repeat every frame while the player remains in contact.

Step 8 — Experiment with triggers

  1. Select Obstacle3.
  2. In its Box Collider 2D component, check Is Trigger.
  3. Create a C# script named TriggerDetector and attach it to Player.
using UnityEngine;

public class TriggerDetector : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log("Player entered trigger: " + other.name);
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        Debug.Log("Player exited trigger: " + other.name);
    }
}

Press Play and move through Obstacle3. The player can pass through this obstacle, but Unity still detects the overlap. Triggers can be used for collectibles, checkpoints, doors, and similar interactions.

5. Student Activity — Collision Experiments

Predict the outcome, test it in Unity, and record your observations. Restore the original settings after each experiment.

ExperimentPredictionActual Result
Remove Player's Box Collider 2D  
Disable Is Trigger on Obstacle3  
Enable Is Trigger on a wall  
Change Player speed to 10  
Disable Freeze Rotation Z  

Reflection Questions

  1. What happens when the player touches a wall?
  2. What happens when a Collider2D is removed?
  3. What is the difference between a collider and a trigger?
  4. Why does the player need a Rigidbody2D?
  5. How can collision detection improve a video game?

6. Programming Challenge

Improve your Collision Playground. Check each task as you complete it.

Bonus: Create a special obstacle that changes the player's color when touched.

7. Common Problems and Troubleshooting

ProblemPossible Solution
Player moves through wallsCheck colliders; make sure Is Trigger is unchecked for solid walls.
Player does not moveCheck the movement script, input handling settings, and Console errors.
Player rotates on impactEnable Freeze Rotation Z.
No collision message appearsConfirm CollisionDetector is attached and physics components are configured correctly.
Trigger message does not appearCheck Is Trigger on the obstacle and Rigidbody2D on the Player.
linearVelocity compiler errorUse velocity in older Unity versions.

8. Knowledge Check

Choose the best answer for each question. Select Check Answers to see your score and explanations.

1. Which component defines the physical boundary of a 2D object?
2. What does Rigidbody2D allow a player to do?
3. What happens when Is Trigger is enabled?
4. Which method detects the beginning of a physical collision?
5. Why is Gravity Scale set to 0 in this lesson?

9. Grading Rubric

CriteriaPoints
Player created with Rigidbody2D and Box Collider 2D15
Four walls configured correctly15
Three obstacles with colliders15
Player movement script works20
Collision detection messages work15
Trigger detection experiment completed10
Written questions and experiment table completed10
Total100

10. Submission Requirements

  1. Completed Unity project or project folder, as directed by your teacher.
  2. Screenshot of the Collision Playground showing the player, walls, and obstacles.
  3. Screenshot of the Unity Console displaying collision messages.
  4. Copies of PlayerCollisionMovement.cs, CollisionDetector.cs, and TriggerDetector.cs.
  5. Completed experiment table and reflection questions.
Success criteria: The player moves with keyboard controls, stops at solid walls and obstacles, and displays collision and trigger messages in the Unity Console.

11. Lesson Summary

You learned to create a 2D environment using Unity's collision detection system. Rigidbody2D and Collider2D components provide physical interactions, while C# event methods detect contact and overlap. These skills form the foundation for walls, mazes, collectibles, obstacles, enemies, and checkpoints.

Next Lesson — Lesson 10: Collect Objects Using Triggers. Create collectibles, detect pickups, remove objects from the scene, and implement a scoring system.