Introduction to Physics in Unity

Objective: Introduce Physics in Unity

Unity provides its own built-in physics engines. These can be used on 2D, 2.5D and 3D games. This is very beneficial as what use are games without physics. Without physics there would be no player interaction with envoirnments, enemies, props or even gravity.

When using physics in Unity it comes down to two main component types. These are colliders and rigidbodies.

Colliders come in many forms. Box, capsule, circle mesh and so on. These colliders are what detect phyical collisions in the game, whether it be lasers hitting an enemy, the enemy crashing into the player or in other games a players character knowing there is a floor.

These colliders are applied to game objects by default but that doesnt mean they will instantly work to detect collisions. There has to be more adjustements for example being set as a trigger. There are two types of collisions. Hard surface collisions are those that simulate a collision like one object bouncing off another. Then there are trigger collisions for when you have collectables like power ups, health or lives. Triggers are more like passthrough objects rather than acting against a collision like landing on a jump tile where the tile stops the player falling down a hole.

Box collider with inactive trigger

For the 2D game we need to set the player, enemy and lasers all as triggers so that they’re not gonna reflect or bounce off each other. Instead we set triggers so that they can pass through and using logic to detect this destroy the object or reduce lives or health using code(more on these ontrigger events in the next post).

The next part of using physics comes down to rigidbodies. Unity provide two types for 2D and 3D. Unlike colliders, rigidbodies don’t come with each object. In fact rigidbodies can be performance intensive when there are a lot of game objects with rigidbodies so best practice is to logically assign which objects would be given them to reduce resource usage.

Unitys rigidbody elements do come with default attributes such as UseGravity. This will simulate gravity and will cause whatever game object that has the attribute applied to fall towards the bottom of the screen when the game runs. For the 2D spaceshooter we don’t want this applied by default on all game objects with rigidbodies will have to have the UseGravity disabled as we are creating our own logic.

Rigidbody with Use Gravity applied

In the next post we will look at different trigger events and when to use them.

Developer