Day 11: Collisions and Triggers in Unity
We can start by adding a red square as a new prefab, and add some code so it will move downward and wrap around the screen.
No we add a rigidbody to the enemy prefab. This is important! Collisions only work if there’s at least one rigidbody present in the collision. Then lets add box and capsule colliders to the player and all prefabs we have so far, so they all physically collide with each other. This causes some strange behavior.
By default, colliders will prevent other colliders from moving into them, and will also causes forces that rotate them around. This is great for ensuring objects don’t phase through the ground in a platformer game, but for this space shooter game, we’d rather them not interact in this way.
Any collider can be a Trigger. This type of collider does not actually physically exist like a real object, but instead presents a sort of “zone” that other objects can detect, instead of interacting with it physically. We can see the option for setting a trigger in the collider settings.
Although triggers can’t cause real collisions, they can be detected using scripts. We need to do a little more setup in the inspector for this to work. Both the laser and player need to be tagged as their respective type. We can create a new tag for the laser as well. Finally, make sure both of their colliders have their “Is Trigger” box checked.
Now lets open up the Enemy script and add a new method that will detect these trigger colliders.
This OnTriggerEnter2D method will automatically run when the enemy encounters a collider that is a trigger. Then, based on whatever it hit (which we can determine by the other object’s tag), it will cause various effects to happen based on the code. For now, we will just destroy the enemy and any lasers it hit.
We can see that the enemy script detects both of the laser and player triggers, both of which destroy the enemy and leaves a console message in the bottom left. We can do anything we want with these triggers, just as long as we know how to put it into code!