Using Physics In Unity

Kenny Pruitt
Unity Coder Corner
Published in
3 min readFeb 28, 2023

Objective: Use Physics Interactions To Kill Enemies

To make lasers hit the enemies and kill them, first our lasers need to be able to interact with the enemies. To do this we can use Triggers. On the laser collider we can simply click the Is Trigger bool to make it true to turn the hitbox into a trigger.

Then on the Laser script we can add the function OnTriggerEnter.

This function will grab anything with a collider that is on a Layer that can be interacted with. To check to make sure 2 Layers can interact, first you can see the layer of an object in the inspector window.

Then open in Unity open Edit — Project Settings — Physics and scroll all the way down and you will see the Layer Collision Matrix which will show what layers can interact with each other.

Now to set up the OnEnterTrigger function, when a collider that can interact with the trigger enters the trigger space it will run the OnEnterTrigger function and grab the collider that interacted with it. If we want the Laser to interact with it, we could then check if the object that entered the trigger has an Enemy component on it.

By doing this we can tell specific information to something that interacts with the laser. For now we can say if the laser interacts with the enemy to destroy the laser and the enemy.

I ran into an issue here, because I forgot that for the interaction to happen I also needed to add a Rigidbody component, which is basically just a physics body to add to the Player and Enemies and turn off the Gravity bool, and turn on Is Kinematic.

Now we can destroy the enemies with our lasers.

Just to make it a little more visually appealing we can add a little explosion effect when they are destroyed with a particle system. To do this all I need to do is create a particle effect and make it a prefab that will spawn in the position of where the ship is when it is destroyed.

--

--

Unity Coder Corner
Unity Coder Corner

Published in Unity Coder Corner

UCC is the one stop shop for everything Unity3d. From tutorials, to news, to opinon pieces. Find everything related to Unity3d here.

Kenny Pruitt
Kenny Pruitt

Written by Kenny Pruitt

Unity Game Developer, C# Developer, and Software Engineer