Now that the rigidbody components have been added, a way to detect the collision type and what to do about that collision needs to be implemented. To do this the collider needs to be changed. As seen in Enemy creation part 1 when the objects collide they bounce off each other and some strange effects can happen.
These strange effect can be resolved by understanding how Unity can deal with collisions. Lets take a look at what the Unity Documentation says about two different methods of handling collisions.
The scripting system can detect when collisions occur and initiate actions using the
OnCollisionEnter
function. However, you can also use the physics engine
simply to detect when one collider enters the space of another without creating a collision. A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object and will simply allow other colliders to pass through. When a collider enters its space, a trigger will call theOnTriggerEnter
function on the trigger object’s scripts.
To get the behavior intended for our gameobjects the colliders need to be changed to is Trigger within the Unity editor. This will allow the items to pass through each other and register the collision within Unity giving the opportunity to add some game logic to the collision. This will need to be done for all three objects the Player, the Enemy, and the Laser.
After doing this the objects pass through each other and this collision can be captured by Unity.
This collision can now be seen by the Unity editor and some logic can be added using Unity’s
Inside this method we can use the
and
Wrapping these in an if statement and using Unity’s tagging system allows for an easy way to target what it is that needs to be destroyed. To save some steps ensure that the tags are added to the prefab, otherwise the changes will need to be overridden into the prefab.
Tagging the laser and wrapping it in an if statement to destroy both the laser and the enemy would look like
The same can be done for the Player but rather than just destroying the Player and the Enemy upon collision lets do something a bit different and implement a rudimentary Lives system. To do this we will need to communicate between different scripts as the enemy will need to tell the Player that it has lost a life upon collision.
We will look at how to accomplish this in Enemy Creation Part 3.