Space Shooter 2D — Part 4

Michael Hatfield
3 min readApr 13, 2022

An Introduction to Physics in Unity

Did I just hit something???

The physics system in Unity is very robust and adjustable for just about any situation you can think of. There are times when you need to know if the player has hit (or been hit) by another object, or you might just need to know if two objects are overlapping or occupying the same space in order to trigger another event. In my Space Shooter 2D game, for example, I need to know when the laser bolts hit the enemy as well as when the enemy ships collide with the player. So I set the colliders to detect this (but not to react like a true physical collision) by setting the ‘Is Trigger’ setting to true and adding the Rigidbody component. This component will allow the game object to be acted upon by the Unity’s physics engine. However, I want to have some control over them motion of the game object so I disabled the ‘Use Gravity’ option. This turns off the force of gravity and allows us to control the object’s motions in a much easier way.

I also added the same components to the enemy game objects so that I can detect if and when they collide with the player object. Again, I used the same settings; ‘Is Trigger” in the collider component will allow me to detect any collisions between the player and the enemy but will allow ME to control exactly what happens through code and not necessarily the physics engine. I also turned off the ‘Use Gravity’ option in the Rigidbody component to let me control the motion of the game object in 3-D space.

Here is how it works if you leave gravity turned on. The white sphere does not have a C# script attached but it does have a Rigidbody component with ‘Use Gravity’ turned on. When the game starts, the sphere begins to fall just like an object would in the real world and, since nothing stops, it keeps falling, accelerating downward.

Detecting a collision and triggering an event is simple, BUT if you want to know who hit who (or whom) then it will help to add ‘tags’ to the objects. These tags can be accessed via code in the triggered events and can allow you create logic in your code to act differently depending on which objects collided.

Some tags are already created by default (such as Player) but adding your own custom tag is very easy.

With just a few lines of code in the enemy.cs script, I can check to see what other object just collided with the enemy object and print its tag to the console.

In the next article I will cover more on the Unity physics and collision system, discussing when to use triggers and when an actual collision event might be a better choice. Till then take care and have a great day!