To understand physics in Unity, its important to understand 2 components, RigidBody and Colliders. Unity uses Nvidia's PhysX engine for 3D, and Box2D for 2D objects out of the box.
When adding a RigidBody component to a GameObject. It will start interacting with the physics engine. For example, gravity will start affecting the object and it will fall when the game runs. The physics engine runs much more frequently than the framerate of the game. Every time the physics engine takes a step, it calls the FixedUpdate() method in MonoBehaviours. It’s a good practice to put any calculations including physics in the FixedUpdate() method.
Adding a collider component gives the GameObject boundaries that collide with other objects with colliders in the scene. Adding a Colliders also activates these Unity messages in MonoBehaviors in objects with colliders:
This function will run once at the moment the collider collides with another collider. The Collider object passed to the method includes information about the collision, including a reference to the other GameObject that collider with this collider.
This function will run continuously as long as the collision is still happening. A Collision object is also passed to it with information about the collision happening.
This function will run once as soon as the collision stops. A Collision object is also passed to it with information about the collision that ended.
Combining RigidBody and Colliders
If two objects with RigidBody components and colliders collide, they will react as you would expect 2 objects would interact in the physical world. Changing variables, such as Mass, in the RigidBody component will change the behavior of the GameObjects colliding.
Physics can be fun to play with and a quick way to prototype a game, but they are also taxing on processing resources. Physics are also unpredictable. So if your game depends heavily on predictability, then physics might not be the right option for you. To learn more check out Unity physics documentation.
Please check our full video covering this topic in our video beginner series for Unity.
Top comments (0)