In order to make a collider into a
trigger we simply check the
'Is Trigger' checkbox on the component
settings in the inspector.
When a collider is a trigger things will
no longer bump into it. Instead they will
pass through it and this can be detected
via code.
Similar to normal colliders,
events are called when other colliders
are overlapping with the trigger collider.
In this example we have a box collider
with Is Trigger checked
and a falling 'prop samoflange' ball object.
This object enters the trigger,
stays as it rolls forward and then exits.
To check these events we attach a script
to the trigger, which is registering
OnTriggerEnter and logging to the console
and likewise OnTriggerStay
and OnTriggerExit.
So if we pause the game
and step through one frame at a time,
looking at the console will show that the
object enters the trigger
stays for a number of frames
and eventually exits the trigger.
In the same way as standard collisions,
one of the two objects must have a rigidbody.
It's standard practice to make sure that your trigger
colliders are static objects,
meaning they will not be moved by the
physics engine. So usually you will make
a trigger and then pass a rigidbody
through it. This example is no different.
We're passing our rigidbody object
through the trigger zone and detecting
when something enters that trigger.
So the intention with the trigger collider,
also known as a trigger zone,
is that you can call code without the
objects in your game physically colliding.
So for example, with our hoverpad,
we can add a force to our samoflange ball
to give the effect of it hovering
so long as it stays within the trigger zone.
For example, we could address the object
that's currently staying within the trigger
because the object that's staying
is saved in a variable called 'other'
of type Collider. We could then address
the rigidbody and add a force
in the direction of Vector3.up,
a shortcut for 'up' in world coordinates.
We could then multiply by a number
which we'll save as a variable.
And we'll finish out the AddForce
by choosing acceleration as the mode.
Now we'll move our object over the hoverpad
and we'll use Freeze Position to keep it
in the same place in X and Z.
Allowing the force of Y to create
the hovering effect.
And now if I press play, as you can see
as long as it stays within that area
it creates the effect of hovering without
having to interact without any part
of the geometry.
Subtitles by the Amara.org community