In this lesson, you will learn how to use the Physics Layer Collision Matrix to dictate which categories of objects should physically collide and which should simply pass through one another.
Why Use a Collision Matrix?
In complex games, you often have objects that shouldn't interact. For example, your player’s bullets should hit enemies but fly right through the player or friendly NPCs. Instead of writing complex if statements in your OnCollisionEnter code to check tags, you can tell the physics engine to ignore those interactions entirely at the system level. This is not only cleaner for your code, but it is also much more performant because the physics engine stops calculating those collisions before they even happen.
Configuring Layers
Before using the matrix, you must assign your GameObjects to Layers. You can do this in the top-right corner of the Inspector window of any GameObject by clicking the "Layer" dropdown and selecting "Add Layer."
Once your layers are defined (e.g., "Player," "Enemy," "Projectile"), you configure their relationships:
- Go to Edit > Project Settings > Physics.
- Scroll down to the Layer Collision Matrix.
- You will see a grid where each layer is listed on both the axes.
- Simply uncheck the boxes where you want to disable collisions. For instance, if you uncheck the intersection between "Projectile" and "Player," your bullets will never trigger a collision event with the player.
Practical Impact
Because this happens in the FixedUpdate physics cycle, it is highly efficient. By filtering these interactions early in the simulation pipeline, you reduce the number of calculations the CPU must perform. You can still use triggers if you need logic to fire without a physical "bump," but for pure physical interaction, the Collision Matrix is your primary tool for optimization and game flow.
Note that this only controls physical collision detection; if you need to detect an overlap for a sensor without a physical bounce, ensure your objects are set as "Triggers" in their Collider components, which the matrix also respects.
Key Takeaway: The Layer Collision Matrix allows you to globally disable specific object-to-object collisions, resulting in cleaner code and improved physics performance.