Space Shooter 2D — Part 5
Collision Detection vs Trigger
Did I just hit something else?
In my last article I explained and demonstrated how I was using the physics engine in Unity to detect when objects collide. Here, I’d like to talk about the ‘Is Trigger’ setting works and when to use it. So, I created a very simple Unity project to demonstrate this. Imagine it is a block buster game where the player must trigger a trap door to open by dropping a spherical rock down a long chute.
Anyway, here is what is happening behind the scenes…
The blue platform has a Rigidbody component with the ‘Use Gravity’ setting turned off and the ‘Is Kinematic’ option checked so that it does not move:
The sphere has a Rigidbody with gravity turned on(which is the default setting) and no other changes. The Unity physics engine controls everything for us, so all we have to do is script the behavior we want to take place. In this demo, the sphere will fall due to gravity and then land on the platform. Since the sphere is, well, a sphere, and the platform is slanted, it will being to roll faster and faster until it falls off the lower end if the platform.
The red cylinder represents a button or ‘trigger’ that we want to fire off some event when the sphere passes through it.
The code for the sphere:
The code for the cylinder to detect when the sphere collides with it:
So there you have it. A very quick and simple demonstration of the differences between realistic collisions and triggering collisions.
Tomorrow I will be making the enemy ships in the Space Shooter game do damage to the player’s ship if they collide. This will mean that the enemy script must talk to the player script. Join me then!