GameDev : Physics and Collisions (Part II)!

After we set our scene, we need to create a behaviour inside OnTriggerEnter method.
Now, what do we want from this behavior?
We have written code inside Enemy script and Enemy can collide with Laser and Player.
If we collide with Player what happen?
And if we collide with Laser?

Again, Pseudo Code first, and we divide a big chunk in little pieces

If you look at the player piece, there is a part where we DAMAGE the player. This is because the player will probably have a life system, maybe we can take 3 hits before we die, or something like that.

Starting with first part : we have to check if OTHER is Player or Laser, right?
But how can we know what type of object collide with us?

Let’s introduce another important topic called TAG. The tag is the way to DEFINE THE OBJECT.

Look at this : if we go in Player’s inspector, there is a little menu called TAG.

As we can see, we can change TAG of object directly in the Inspector. By default, Unity has some Tag which can we use, but if we need specific we can create them without any problems.

To create a new Tag, go in the same menu, click at the bottom on Add Tag.
Then click on + button, write a name and Save.

After this we have to GO BACK AND CHANGE TAG, it is not AUTOMATICALLY UPDATE

We can see the new tag added to the List.
I name it “Asteroid” because in our game maybe in the future we add some asteroids, and in our trigger we need to define asteroid with tag so we can check various collisions.

Now that we know how, we need to create a tag for Enemy and for Laser.

And apply

After this, we have to check in code the collision.

Let’s start with an IF statement, so: Is OTHER gameObject a laser or an enemy?
Verify by TAG and run the code if it is!

You see here : we have two methods for checking tags.
We can use
other.gameObject.tag == “Player”
or
other.gameObject,CompareTag(“Player”)

This has same meaning, but in term of performance, if i not wrong CompareTag is better.
Expecially inside a Trigger / Collider or if we develop on mobile device.

At this point we don’t talk yet about performance, but this is a topic we need to understand very well in the future.

Back to our project, use CompareTag, and if we look at Intellisense, inside CompareTag method we have to pass a data of type string.

For now let’s try to destroy both the player and the enemy, in the next articles we will set up the Life and Damage system.

To destroy both

Test it

And everything works!
And now we set the same for Laser

Press Play

And everything works again!

In the next section we will set up Life and Damage system!!

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!