Making things go bump in the night
Today we look at physics in Unity. Just the basics, including collisions, triggers, and rigid bodies. Let’s get to it!
So how to we detect interactions like collisions between our objects in Unity? There are several components needed to achieve this. We’ll start by discussing the collider. Colliders come in a few forms like the Box collider and the Capsule Collider (two types of collider that we have been using in our space shooter game so far). As you may have inferred, most of Unity's colliders are differentiated by their geometry. They can also be marked as being a trigger or not. We will cover this distinction more in a moment. Colliders alone don’t necessarily allow us to determine when (and how) objects interact in our games.
For most interactions involving colliders one or more of our objects also require another component. That component is the RigidBody (and its 2D counterpart, the aptly named, RigidBody2D). The RigidBody component also allows us to apply other types of physics like gravity to objects. A RigidBody component, by default, has gravity turned on and will cause the object to interact with the gravity settings of the environment, in the default case this usually means that the object will fall once the game is started. For the purposes of our space shooter objects we turn gravity off so that we can control the movement of the objects ourselves.
Types of collision
There are also 2 types of collision in our Unity physics system. Hard Surface collisions and pass-through, or trigger collisions. We can think of hard surface collisions as the type of collision that occurs when two cars crash into each other or when you bounce a ball off a wall. Pass-through, or trigger collisions are more like walking across a trip wire, you continue moving but it has triggered something else to happen by doing so. Both types of collision require a RigidBody to be attached to at least one of the objects involved in the collision. The hard-surface collision additionally requires that the RigidBody be non-kinematic. Kinematic RigidBody objects do not have their movement controlled by the physics engine and usually have their position controlled through script.
A hard surface collision contains information about the collision itself like touch point, force applied, etc., A trigger, in contrast, doesn’t affect physics directly and can be handled like an event (for instance, when the player reaches a certain point something else happens).
Below is the chart that Unity provides for how RigidBody objects and Colliders interact with each other. We’ll delve a little deeper into this tomorrow.
Today we’ve peeked under the hood at the basics of the Unity physics system. Tomorrow we will delve into the difference between the events these collisions raise and when to use one versus the other. If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.