Interacting via Collisions

Cliff Bailey
3 min readJul 14, 2022

While we’re setting up a relatively simple system of interactions with the enemy, there’s still a lot that goes into it.

First, let’s hit it with collisions.

There are two general kinds of collisions we’re working with in Unity:

  • hard-surface collisions — think throwing a ball at a wall; using physics
  • trigger collisions — or pass-through collisions; these trigger a change of some sort such as when you collect a power-up

And there are two specific collisions we’re coding:

  • between laser and enemy
  • between player and enemy

Add a collider to both the laser and enemy objects and check Is Trigger.

Add a Rigidbody to the laser and uncheck Use Gravity.

Repeat for the enemy.

Now let’s add this bit of code to the bottom of the enemy script:

So now, when something other than the enemy enters the enemy collider, the console will display the phrase “Hit:” and the name of the object that hit it as seen below:

Note the console messages.

COLLISIONS AND CONSEQUENCES

So let’s make some stuff happen.

Here’s what we’re aiming for:

// if other is Player
// destroy enemy
// minus one life

// if other is Laser
// destroy enemy
// destroy laser

We’re going to use Tags.

Assign the Player tag to the player, the Enemy tag to the enemy, and then add and assign the Laser tag to the laser.

And now let’s make the following amendments to void OnTriggerEnter:

And you’re ready to go!

--

--

Cliff Bailey

Software Developer w/ADHD learning and doing life.