When Worlds Collide
Now I have this song stuck in my head, but aside from that we’re gonna talk about objects colliding with one another:
So what I wanna do is when the enemy runs into (or collides with, wink wink) our Cube, it will be destroyed as well as do damage to our Cube’s shield. We also want the laser to destroy the enemy as well.
This little option sits within our “InsertShapeHere Collider”. To allow for our code to work we need to understand that Collider needs a Rigidbody component attached to the object, and that Rigidbody component needs to not Use Gravity because we’re a space-cube… in space. So let’s get our Enemy and Laser Prefabs setup with those prerequisites: Make sure you turn on “Is Trigger” or the GIF above will be your fate, promise me… I had a heck of a time figuring out what was wrong.
So while looking through the Unity Documentation for Collider I found OnTriggerEnter, which is called by Unity when two GameObjects collide. So upon typing out our Method, “other” appears… what is “other”? Well, in the documentation it explains that it is, “The other Collider involved in this collision.”. So if the Enemy collides with the player, other = player. “other” is also a renamable variable, so put whatever you want there, but for learning purposes I will leave it be. The important thing to note is that “other” stores the information of the object that it is collided with during the time it is collided, which is very important for our next step because we’re going to need to access the Player cubes shield health to reflect being damaged! Oh yeah, let’s get a simple Method set-up for that right now!
While I was adding Shield Health I realized I wanted to add some form of Shield Recharging so… I added that in! It’s almost identical to the Ammo Reloading, and that’s cool because I’m starting to enjoy that things are similar.
But there we have our new variables, our Methods being called in Update() all tidy, as well as our Methods being explained. You should notice one difference though, and that’s that I used a public void for _playerLife, why? If you remember, anything that is public can be accessed outside of the script… and since the Enemy script needs to access the Player to damage it… yeah, you get it.
Next we need to figure out how we can identify what object we’re colliding with so, we’re back in the Collider Unity Documentation and we have a variable called Tag, which needs to be set in the Tags and Layers. Tag will allow us to more easy identify our GameObject being collided with, so let us set one for our Laser, Enemy and Player (Cube) and name them as such to avoid confusion.
Adding tags is quite simple as well, which will be needed in some cases. Whenever you go to select a Tag, hit Add Tag… hit the [+] in the bottom left corner of the Tags drop-down box, name and Save your tag. Then select it as you would.
Alright, so we’re all set-up, let’s check everything out!