In this lesson, you will learn how to use physics layers to selectively ignore collisions between specific game objects while maintaining their interaction with the environment.
The Problem of Unwanted Collisions
Imagine your game features a player character and a fleet of "ghostly" collectible pickups. You want the player to move through the environment, but you don't want the player to physically bump into the pickups and knock them over. If you simply turn off the colliders, you lose the ability to detect when the player touches them. This is where Layer-Based Interaction Filtering becomes your best friend.
How It Works
Physics layers allow you to categorize your game objects into groups. By default, Unity checks every object against every other object for potential collisions. However, you can tell the physics engine to ignore specific pairs of layers using the Collision Matrix.
- Define Layers: In the top-right corner of the Editor, click the Layer dropdown and select Edit Layers. Add two new User Layers:
PlayerandCollectible. - Assign Objects: Select your player object and set its Layer to
Player. Assign your collectible objects to theCollectiblelayer. - Configure the Matrix: Navigate to Edit > Project Settings > Physics. Scroll down to find the Layer Collision Matrix. You will see a grid of checkboxes representing every layer combination. Uncheck the box where the
Playerrow intersects with theCollectiblecolumn.
Implementation Tip
Even with the collision disabled in the matrix, your OnTriggerEnter events will still fire if the collectible's collider is set to Is Trigger. This creates the perfect setup: the player passes directly through the object (no physical bouncing) but can still trigger collection logic via script:
void OnTriggerEnter(Collider other) {
if (other.gameObject.layer == LayerMask.NameToLayer("Collectible")) {
// Collect the item!
Destroy(other.gameObject);
}
}
By leveraging the Collision Matrix, you keep your physics calculations lean and clean, ensuring that objects only interact with what truly matters for your gameplay mechanics.
Key Takeaway: Use the Layer Collision Matrix in Physics Settings to define which object categories can physically touch, allowing you to ignore unwanted collisions while keeping trigger detection fully functional.