Physics and Collision In Unity

No game is complete without interactions of some kind, and in Unity we build these systems with trigger and collision messages included with the MonoBehavior method. Unity utilizes two forms of collision. Hard collisions, such as car crashes, are handled by calling “OnCollision”. Pass through collisions involve aspects like a consumable power up. To use these we call “OnTrigger”.

Before we can use any physics in Unity we must first ensure all game objects involved are triggers. In the game object’s inspector panel there will be a collider component. Under that “is trigger” must be checked.

Another prerequisite to create interactions is a rigidbody. At least one of our game objects involved must have a rigidbody component. This will cause the object to utilize Unity’s physics engine. We can uncheck “uses gravity” for this example.

Before we write any code, it’s a good idea to give the game objects we want to interact a tag. We can call this tag in code later.

In this example we will make the player’s lasers destroy approaching enemies. To do this we will use the script tied to our enemy prototype. Create an if statement that will only run when it detects it collided with the laser. The information on who collided with us is stored in “other”. Last, we use the static method, destroy, to remove the laser then our enemy.
