An Introduction To Physics in Unity

Austin Hall
3 min readSep 2, 2022

--

It’s important to remember that nothing exists in the game until we create it. We create our objects like our player, enemy and laser. We also are responsible for creating the physics of the world in which our player lives. Things like gravity, or damage when getting hit. We accomplish this in Unity by using the Box Collider and the Rigid Body components.

Box Collider and Rigid Body components

When it comes to collision in Unity, there are two forms of collision. there are hard surface collisions, like a car crash, or throwing a ball at a wall and having it come back to you. We also have trigger collisions. Some examples of trigger collisions include walking over a coin to pick it up or driving through a power up to activate it.

creating collisions and damage

Above is an example of trigger collisions. For this we will need a rigid body. It is important to determine who gets the rigid body. Not every object needs a rigid body, and to many rigid bodies can make your game performance intensive.

We’re using the OnTriggerEnter() function to Identify and implement our collision, as seen above. If we go to the Unity Scripting API we can find a description of the OnTriggerEnter() method. Pay special attention to the note, which states that both objects must have a collider component but only one needs a rigid body component.

Enemy script, checking for collision from player and laser

We set the object tag in the inspector window. Be sure to select the prefab object not the hierarchy object. In the Enemy script, we create our trigger method and use other.tag to check for collisions with the Laser and Player.

Player script, creating Damage method

We can implement a lives system in the player script by creating a variable, decrementing that variable on collision and destroying the object when the variable reaches zero.

Enemy script, getting player component and calling damage() method from player script

“Player player = other.GetComponent<Player>()” gets the root of the player object and allows us to use the methods from the Player script in the Enemy script. Running this script will call the Damage() method from the player and decrement the lives variable every time the player and enemy objects collide. When the lives reach zero, the player object is destroyed.

--

--

No responses yet