Day 8: Handling Collisions In Unity
So right now we have our player moving around with input from our end-user. We have an enemy that moves down the screen. We have lasers that fire out of our stunning, brave cube. We need to figure out a way to have all these game objects communicate. Unity handles things like this with collision. The Player, the Laser, and the Enemy all have collider components.
In short we need to make sure these components’ “is trigger” parameter is set to true.
There are collisions, and there are trigger collisions. We want trigger collisions because we want to give the illusion that these objects were penetrated by the object it collides with. Our goal is to have the Enemy be destroyed when it collides with the Player. We also want the Enemy and the Laser to be destroyed when the Laser collides with it.
To achieve this we need to use the OnTriggerEnter() method.
Lets just start with the method for now. We will get into all the rest of this code later on.
Void OnTriggerEnter(Collider other). This function takes 2 arguments. The collider and “other” stores the information for which object collides with this game object. Lets check to see if our collision is working properly. Lets Make an if statement that checks this.
Debug.Log(“Hit: “ + other.transform.name);
Run the game and let the Enemy hit the Player. you should see this message in the console.
Lets remove that Debug.Log and add some logic that will destroy the Enemy when the laser comes into contact with it. We’re going to accomplish this by using tags.
We’ve tagged our Laser as “Laser”, our Enemy as “Enemy”, and our Player as “Player”. The rest of the code in the photo above is what helps us accomplish the goals we set.
We have to check to make sure the Player isn’t null. If the other.tag == “Player” and it is not null, Damage the player. We have a method in our player script called Damage(). We reference it here in the collision detection section of our Player script.
So when the collision occurs, take away 1 life with the
_lives--;. We are starting with 3, so when the player collides with the enemy 3 times the player game object is destroyed. We are representing the number of lives with a variable called _lives.
private int _lives = 3.
The laser and enemy are both destroyed on that collision since we do not have any lives set up for enemies and lasers. That is being represented here:
Its that simple! Hop into Unity and run the application. COLLSIONS!! This is finally feeling like a game!