Day 10: 2D Physics in Unity
Today we’ll be looking a Unity’s built in physics system and how to use it. It’s actually quite easy to make a realistic simulation of physical objects like this:
This can be done in either 3D or 2D space. This article will cover 2D physics, both for simplicity, and because it will help with the 2D space shooter game that we’ve been working on.
To make this simulation, we start a new Unity project, create a 2D square and scale it to create ground, and create another square prefab for the yellow box. Now we can add gravity so the box falls. Instead of doing so using a C# script, we can just let Unity’s physics handle it by adding a Rigidbody component to the square prefab.
This grants the square physical attributes like mass and the ability to freely move in space. Now it will fall downward when we run the game:
Unfortunately, it falls through the ground. That’s because there is nothing that detects when the square and the ground collide. To fix this, we need to add a Box Collider to the square and the ground, so Unity’s physics will automatically detect when they touch each other and prevent them from moving through each other.
After adding Box Colliders to both the square and the ground, now the square will fall and stop when it hits the ground.
Now there’s a little more we can do to make this more interesting. Box Colliders can be assigned a Physics Material that specifies more about what happens when it collides with another object. We can create one by right-clicking assets, navigating to Create->2D->Physics Material 2D. Then, we can set its “Bounciness” to 0.5 and apply this new Physics Material to the square’s collider.
Now when we run the game, the square will fall and bounce off the ground.
Feel free to experiment more with adding new objects to the scene and watching them bounce off each other. It’s a lot of fun!