Before we look into adding enemies to our game, it’s important to know how the physics system in Unity works so we can easily detect collisions between our different GameObjects.
Unity gives us 2 types of component that are required to be able to make use of the in-built physics system. These are the collider and the rigidbody. It is important to note that both types have 2D and 3D variants.
For example —
The collider is the component that allows a collision to be noticed by the physics system.
Many of the Unity primitives come equipped with an appropriate collider when we create them — If you’ve been following along, check your Player GameObject and you should have a 3D Box Collider already provided. We’ll stick with the 3D variants for now, they can be easily swapped out when we start implementing some of our sprite assets for the game.
As I mentioned, we also need a rigidbody component —
The rigidbody is the component that allows forces to be applied to our GameObjects. This could be by way of several different methods available or even simply applying gravity to the GameObject.
NOTE: More information on the rigidbody component and it’s various methods can be found in the scripting API.
It is important to note that for a collision to occur, BOTH objects involved in the collision must have a collider attached. While only ONE of the objects involved requires a rigidbody.
Rigidbodies can be resource intensive components so it’s advisable to place them on the objects that have fewer instances of them. For example, if we’re looking to detect a collision between the Player and an Enemy — our Enemy will be a prefab and as such will be copied many times, if the Enemy has a rigidbody, you’re creating as many rigidbodies as you have Enemies on the screen. This would not be an optimal approach and could lead to a laggy game experience, the optimal approach would be to have the rigidbody on the Player so we can still detect that collision with the fewest number of rigidbodies being created.
In my next article, I’ll look at the differences between Collisions and Triggers using this Unity physics system.