2D Game Development: Colliding with Colliders

Thomas Kohut
3 min readDec 23, 2021

This article discusses handling collisions between 2D objects using OnTriggerEnter2D.

In the previous article, we mentioned how our lasers to interact with other objects in the environment. For that, we need to add two components: A rigidbody 2D and a collider 2D.

A collider is used to detect a collision with another object. There are two major kinds of collisions: surface collisions and trigger collisions. With surface collisions, the two objects bounce off of each other, like hitting a volleyball or pushing a door open. In trigger collisions, the two objects “pass through” each other. The most common example of this would be collecting an item, such as collecting a coin in Mario or a rupee in Legend of Zelda. These two collisions are determined through the boolean isTrigger which is located in the settings of all colliders. The type of collision also determines what method is used to handle collisions, with OnTriggerEnter used for when isTrigger is true. There are several different kinds of colliders, but in this case we are going to be using a box collider on both the laser and enemy prefabs.

A rigidbody is used to handle physics on an object. It enables the collisions mentioned above in colliders. However, only one of the objects need a rigidbody for a trigger collision to occur. Adding a rigidbody to every object with a trigger event will quickly, so therefore it is more efficient to only add a rigidbody to one object.

After adding the 2D colliders and 2D rigidbody, we can move on to coding the collisions. Luckily, Unity has several predefined method for handling collisions, but for our purposes we will be using OnTriggerEnter2D. In the script handling enemy behavior, add the OnTriggerEnter2D method. It is important to use the corresponding method for the type of collider being used in order to ensure functionality (OnTriggerEnter2D will not work with a 3D collider).

Base form of OnTriggerEnter2D method. Note the collision parameter is referencing the object colliding with the enemy object.

Now that the method to handle a collision has been written, we have to determine what happens once the collision is detected. For now, destroying both the object colliding with the enemy and the enemy itself will suffice. To do this, we have to use the Destroy method on both the enemy and parameter gameobjects.

OnTriggerEnter2D method destroying both the enemy and colliding gameobjects.

We now have a functioning OnTriggerEnter2D method. But what if we want different behaviors to occur when different objects hit it, such as the player? For this, a way is needed to differentiate between what object collided with the enemy. This can be determined through tags, a feature which will be discussed in a future article.

--

--