Unity Physics, Collisions, and Triggers (2D Space Shooter)

Recently went back over the subject of physics, collisions, and triggers within Unity when working on the 2D Space Shooter. Namely, the importance of Unity’s Rigidbody component in allowing a GameObject to react to real-time physics (perhaps most notably gravity via the GravityScale float) as well as react to collisions and be detected by triggers.

In the case of collisions and triggers, at least one of the two GameObjects colliding or intersecting must have a Rigidbody component, but it’s also worth mentioning we should avoid placing Rigidbodies onto GameObjects which don’t need them (as overuse of real-time physics across multiple objects can get expensive very quickly).

For the distinction between triggers and collisions, we’ll want to use collisions when we want to track hard collisions (for example if we want an object to bounce or ricochet off another) and we’ll want to use triggers when we want to track when two objects overlap (creating instead the illusion of a collision). In games, we’ll most likely want to use triggers in detecting when a player’s entered a certain area or perhaps when the player walks through a power-up/pick-up/collectible (without having their movement temporarily impeded by a collision).

A very handy article to take a look at is the Unity documentation on the Monobehaviour base class. Among other things, it provides a comprehensive list of all the methods we can make use of within any of our classes which derive from it (which they do by default in Unity). ‘Start’ and ‘Update’ are of course both on here, but we also have ‘Awake’, ‘FixedUpdate’, and a long list of ‘On_’ methods. The ones we’re interested in here are the OnCollision and OnTrigger methods. All we need to do to make use of these is to write the one we want out within our classes. As a couple examples:

1)

public class EnemyBullet : Monobehaviour
{
private void OnTriggerEnter()
{
// Check to see if object has a tag of 'Player'
// if it does, access the Player script and call DamagePlayer
}
}

2)

public class Bomb : Monobehaviour
{
private void OnCollisionEnter() // whenever a collision is detected
{
Explode();
}
}

In the case of our space shooter, we can apply a Rigidbody to the player’s bullets and colliders to both the bullets and the enemies. We can set the GravityScale on the Rigidbodies to 0, then all we need to do is write out the logic for what happens when a bullet collides with an enemy. We can then either have the bullet’s script detect the collision and destroy the enemy (and then itself) or we can have the enemy’s script detect the collision and destroy the bullet (and then itself).

That’s most of what I have to share at the moment; I’ll try to include a gif of these collisions in action sometime soon!

Game Developer | Game Design and Literature Graduate