My 90 day journey becoming a Unity game developer: Day-6

Rhett Haynes
3 min readMay 28, 2021

--

Objective: Destroying our enemy using trigger collisions. There is 2 different ways our trigger collisions will destroy the enemy. First way is when the player collides with the enemy, and second will be when the player’s laser collides with the enemy. This is the final result:

Enemy being destroyed using trigger collisions.

We are going to add rigidbodies to the Enemy and the Laser. Rigidbody enables our GameObjects to act under the control of physics and make our objects move in a realistic way. For rigidbodies to allow collisions to occur, they must have colliders attached on them to work. Rigidbodies with no colliders will simply pass through each other during physics simulation.

Inside the Enemy and Laser, under Rigidbody we will turn off Use Gravity. This will keep the enemy and laser from falling downward right away when the game starts.

Rigidbody Use Gravity turned on causing the enemy and lasers to fall downward.

With Enemy and Laser, we will also turn on Is Trigger under each one’s collider. This will prevent the Enemy and Laser from bouncing off each other and flying around the screen when they collide. Instead, when they collide, they should go inside of each other which will make destroying them look more realistic.

Collider Is Trigger on, Rigidbody Use Gravity off.

Add tags to the Player, Enemy, and Laser. This will allow us to call upon them inside our code for destroying each game object. For each Prefab tags were added to, make sure to click on Override to save these changes.

Created a tag for the Enemy.
Override changes applied to the Enemy.

Inside our Enemy script under the Update() function, we will use the OnTriggerEnter() function supplied by Unity to detect our collisions. We will detect if the player collided with the enemy, then detect if the laser collided with the enemy. When these collisions happen, the enemy will be destroyed. This is the following code:

OnTriggerEnter() function used to destroy the enemy by player and laser collisions.

Next time we will work on player lives and taking damage. Until then …

--

--