Getting Started with Collisions in Unity

Hi everyone, here we going to get started with implementing a collision system using mesh colliders and rigid bodies. Before we get started I’ll go ahead and introduce the game objects being used. The large blue cube is the player which shoots green capsules which we call lasers. The smaller red cube is the enemy game object which moves downward in order to inflict damage on the player and can be destroyed by a laser.

Every previously mentioned GameObject comes with it own collider component. We call on this component to determine when game objects are in contact.

But, the collider can only be trigger by objects that have a Rigidbody component. As such, we gave the laser GameObject a Rigidbody so that the enemy can detect the presence of the laser and destroy itself. The Enemy GameObject also has its own rigid body so that the Player can detect a collision with the enemy and deal damage to itself. Now lets get into the implementation.

In order to make use of the collider we can crate a method OnTriggerEnter(Collider other). This method is called when ever a Rigidbody object enters the collider and that object gets placed in the variable named other. Here we check to see if the object is tagged as a “Laser”, and if it is we destroy both GameObjects.

The response to an enemy GameObject colliding with a Player GameObject is slightly more complex. In order to deal damage to the player we need to call Player’s Damage method. As such, we need to use GetComponent in order to access the <Player> C# script to access and call the Damage method.

And now everything works as intended. Thanks for reading.

Here I am documenting everything I am learning in order to become a successful game developer.