By default, if multiple game objects are on the default layer, they will all collide with each other. In that case, we can say everything will collide with everything. In game development, often we need to decide which object will collide with which one. For this, we need to define a layer-specific division of game objects. We put each type of object in different layers. In Collision Matrix, for each new layer, a new column and row are added. Matrix defines the interaction between the layers. By default, a new layer collides with all the other layers. A developer needs to set up the interaction between the layers. Using a correct setup, we can avoid unwanted collision.
Let's take a look at an example of setting Collision Matrix for layers:
Layer Collision
.By default, all the objects will appear on the default layer, as shown in the following screenshot:
Using the preceding steps, we can set up a layer-based Collision Matrix.
Create a new JavaScript and attach it to the main camera and run the test.
Write the following code inside this JavaScript file:
#pragma strict function Start () { } function Update () { } function OnCollisionEnter(Collision collisionInfo) { Debug.Log("Detected collision between " + gameObject.name + " and " + collisionInfo.collider.name); } function OnCollisionStay(Collision collisionInfo) { Debug.Log(gameObject.name + " and " + collisionInfo.collider.name + " are still colliding"); } function OnCollisionExit(Collision collisionInfo) { Debug.Log(gameObject.name + " and " + collisionInfo.collider.name + " are no longer colliding"); }
Using the preceding script, you can check which objects are colliding with one another and for how long.
Let's see how we can ignore collision for specific objects using a script. Often, in interactive development, we need to set up rules for collision between objects. For example, we need to set up a rule where projectiles should not collide with the objects shooting them. Although, using custom layer-based collision on GUI, we can define a layer-based game objects collision rule, we also can handle it using a script. We can use IgnoreCollision
Physics of Unity3D for creating Collision Matrix.
The following is the example of a script-based Collision Matrix:
Script-Collision-Matrix
.var bulletPrefab : Transform; function Start () { var bullet = Instantiate(bulletPrefab) as Transform; Physics.IgnoreCollision(bullet.collider, collider); }
Run and test the script, you will see that a bullet is ignoring collision with the shooting object.
18.188.131.255