Enemies and Collision Detection

How to handle collisions?

For today’s article, I’ll be going over how an Enemy is created and how Unity handles collisions using onTriggerEnter function. To create an enemy, I simply created a 3d cube in the scene, applied a red material on the cube, and named it Enemy. Next, I attached an Enemy script and applied the following behavior below:

In the above code, I use the Translate function to move the enemy from its starting position downwards 4 meters per second. Next, I check if the enemy reaches the bottom of the screen. If it does, I teleport the enemy back up to the top of the screen and set a random x position between the left and right edge of the screen.

Triggering Collisions

Behind the scenes, Unity handles the logic of when 2 game objects overlap with one another. In order for Unity’s collision system to take into effect, a Rigidbody component needs to be attached to the Laser game object prefab. Applying a Rigidbody component to a game object enables Unity’s physics system for that game object.

Uncheck Use Gravity here

Also set Is Trigger to true for the laser

Lastly, Unity’s Monobehaviour class has a function we can implement named onTriggerEnter(Collider other) where it gets called whenever a collision is detected between 2 game objects. In the below code:

I check if the other collider is a game object that has the tag Laser.If the above is true:

  • Destroy the laser game object
  • Destroy the enemy game object

Final Result

To view the full source, please visit: https://github.com/hlimbo/Space-Shooter-Tutorial

Thanks for reading!

Software Engineer