13-Destroy Enemy-Collision with Laser and Player using Physics in Unity

Objective: Make the interaction between enemy and the player happen.
- When the Enemy gets hit by the laser, it destroys itself
- When the Enemy runs into the players, it destroys itself

To make this type interaction happen, we need to enable the physics in unity by introducing a Rigidbody component. This will allow us to detect collisions (either a hard surface collision or a trigger type collision).

In our case, we wouldn’t want to see our lasers bouncing around or have any physical forces between objects, so the trigger type collision is what we need here. If we go to the scripting API for the Monobehavior class (the script we attach to a game object and control its behaviors), we can find the method OnTriggerEnter, which will help us detect collision and trigger events that we define.

With the above knowledge in mind, we can start implement this type of interactions in our game from two aspects:

  1. Set up the physics in the inspector, that is, add Rigidbody and collider to the Enemy (note that just one rigid body is needed for the collision to be implemented)

2. Scripting using the OnTriggerEnter method.

The “other” of type “Collider” refers to the object that collides with the current game object. In our case, this other could be Laser or the Player, to identify one from the other, “tag” is added to the laser prefab and the Player, for example:


// if other.tag is Player
// Destroy Enemy (this.gameobject)
// if other.tag is Laser
// Destroy Laser (other), and then destroy Enemy (this.gameobject)

Once the above pseudo-code is implemented, we have the objects interacting with each upon collision (trigger), as show below:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store