Introduction to Physics in Unity & Collisions

Anurag Chawla
3 min readApr 6, 2021

As continue with last article & moving ahead setting up Player, Laser & Enemies in our Prototype for GalaxyShooter 2D.

There are few things to consider.

  1. When Player hit the space key, it will fire a Laser and collide with an Enemy & get destroyed.
  2. Player can also collide with an Enemy or Enemy can collide with Player, so they get destroyed

Player, Enemies and Laser- all three have colliders & these colliders detect the collisions in Physical World, but still we are not hitting with each other or ignoring the collisions — This is because Not Enabled Physics System in Unity

Player, Laser & Enemy — have Colliders

In Unity , To Introduce Physics we need to use Rigid Body, that allows us to add physics properties to Game Object.

Rigid Body is not enough, on top of this there are two kinds of collisions:-

  1. Hard Surface Collision eg: that bounce off when they strike some surface like car crash, ball bounce etc. This can be done if Is Trigger unchecked in the Collider section and Unity have events like OnCollisonEnter.
  2. Trigger Collision eg: when somebody collect like power ups or coins etc. that give us illusion of pass through its a trigger -but not acting on it. This can be done Is Trigger checked in the Collider section of the Game Object. So, this can be done for Laser, Enemy and Player & have Unity methods like OnTriggerEnter Note :Either of the object who collide with each other should have Rigid Body.

Let’s consider for Player, Enemy & Laser — Is Trigger is checked for each of the colliders.

  1. Adding Rigid Body to Laser as shown below.
Adding — Rigid Body to Laser & Use Gravity is checked

Note: When Player hit the space key and fire a Laser, it keep on going upwards as expected, but if Use Gravity Property is checked it will moves down & bounce back up. Here just make sure to un-checked Use Gravity.

2. Either Enemy can collide with Player or Player can collide with Enemy, so it doesn’t matter to whom we can apply Rigid Body. Let’s add Rigid Body to Enemy as shown below and also make sure to unchecked Use Gravity.

Adding -Rigid Body to Enemy

Next on Enemy Script, add On Trigger behaviour and detect collisions as below.

Enemy Script- OnTriggerEnter Event detects who collide with the Enemy- Player or Laser..

As , this script is attached with Enemy, we can found who collided with Enemy from other parameter of Type Collider- It could be either Player or Laser when using the property of transform.name on other i.e., other.transform.name inside the Debug.log() method.

Enemy Object Collided — with Player or Laser (Clone)

This concludes the Importance of Physics in Unity — with Rigid Body & Collisions..!!

@GameDevHQ-Day 9…

--

--

Anurag Chawla

Emerging Technologies - Power Virtual Agents | AI Chatbots | Multi-Cloud & DevOps | UI Technologies - React , Angular | Gaming Technolgies - Unity, XR- AR/VR