Physics is one of those subjects that triggers nightmare flashbacks of my high school days when rolling toy cars down slopes was the peak of intellectual pursuit. If you’re like me, then the notion of learning physics is about as exciting as watching a download progress meter.

Don’t worry: Unity makes physics fun. Its built-in physics engine allows you to easily create games with explosions, guns and bodies smashing into beautiful walls — without having to study a boring textbook.

In this chapter, you’ll learn how Unity’s physics engine works, and use it to add collision detection, raycasts and even bobble heads into the game.

Note: This tutorial is part of a collection that teaches Unity development from the ground up. You can read the entire series over here. This series is free and does not require any account creation. All assets are provided. If you find it useful, feel free to buy me a coffee.

Adding gravity

Open your existing project, or you can open the starter project for this chapter. You can download it here:

https://drive.google.com/file/d/18KbjE3l_aDl9FclArVq1VIWD6hxHabW_/view?usp=drive_link

Currently, the space marine can run around the arena and shoot things. However, with no targets and no ability to turn around, he’s bored and prone to sneak attacks. He also has the superhero ability of walking through walls. You’re going to solve these problems with physics!

First, you need to add a target for the marine. If there isn’t an alien in the scene, add one now. In the Project window, drag an Alien from the Prefabs folder and place it in front of the marine. In the Inspector, set the Alien’s position to (-27.67, 13.57, 74.53). Set the rotation to (0, -180, 0)

This shows the position and rotation of the alien.

Play the game and shoot the alien. You’ll notice that the bullets shoot right through them. You have to opt your GameObjects into receiving collisions. Sound familiar? Can you guess what component you’ll use?

That’s right; you need another Rigidbody! In the previous chapter, you used this component to opt objects into the physics engine. With the Rigidbody in place, not only can the GameObject respond to forces like gravity, but it can get a notification when another object, such as a bullet, collides with it. Then you can define what happens after such a collision, e.g., the alien explodes or vanishes.

Your alien has no Rigidbody, which is why it’s impervious to our hero’s attack. Select the Alien in the Hierarchy. In the Inspector, click the Add Component button. Select the Physics category and select Rigidbody. Don’t change any options. In this case, the GameObject will now react to gravity.

Play your game.

This shows the alien falling through the floor.

The alien falls through the floor. Funny, but not ideal. To fix this, you can either turn off the gravity for the alien or use a collider.

Adding colliders

Colliders perform various functions. They allow you to define the bounds of a GameObject for the purpose of collisions and are also useful for keeping your GameObjects from falling through the floor.

Usually for colliders, you want to use primitive shapes such as spheres and boxes. For example, you’ll make a sphere that’s about the same size as the alien. It won’t match the shape of the alien exactly, but this is usually “good enough” for collision detection purposes and results in a much faster game. If you need more precise collision detection, you can use a mesh collider instead — more on that in just a minute.

First, you’ll stop that alien from dropping through the floor.

Select the Alien GameObject in the Hierarchy and click the Add Component button in the Inspector. Select the Physics category, and, from the components listing, select Sphere collider.

You’ll see the collider, complete with many options, appear in the Inspector.

Here’s the breakdown of the options:

  • The Edit Collider button allows you to move and resize a collider visually in the Unity scene editor. Presently, if you zoom in, you’ll notice that the sphere is much smaller than the alien, and this option would allow you to move and resize it to better represent the alien’s shape.

    Alternatively, you can set the center and radius properties manually, as you will do shortly.
  • The Is Trigger checkbox means that the collider can pass through other colliders. Although the collider doesn’t act like a hard surface, you’ll still get collision notifications.

    A good use case for a trigger is to open a door when a player steps on a certain area.
  • The Material option allows you to apply something known as a Physics Material, which are materials that have physical properties. For instance, you could create a surface that causes players to slide and assign it to ice models to make a skating rink.
  • The Center is a sphere collider’s center point.
  • The Radius determines the size of the collider.
  • The Layer Overrides allow you to opt-out out collisions using layers. You’ll be using layers later in this chapter.

With all that in mind, you can fix the collider for the alien to make it behave.

Adjusting the collider

The alien’s collider is pretty small. You can see it in the Scene view. Simply select the alien in the Hierarchy and press the f key in the Scene view. You should see the outline of a green ball.

This shows the alien's collider showing halfway through the floor.

As is, the player would need to shoot at the alien’s feet. You need to adjust the collider.

In the Inspector for the sphere collider, set the Center to (0.34, 2.54, –0.57) and the Radius to 2.52. Check out the Scene view now.

This shows the full sized collider.

Click the Edit Collider button to see control points along the collider. You can select those points and drag to either increase or decrease the size of the collider. This is how I came up with the radius and position values you entered a second ago originally — just sizing it until it was an approximation of the alien’s size. Feel free to play around with the placement of the collider, and then undo to get back to the original size.

Now that you’ve made your changes, you’ll want to apply them to other Prefabs. Do you remember how to do that? Take a moment to try.

In case you forgot, make sure the Alien GameObject is selected. In the Inspector, click the Overrides dropdown and select the Apply All button.

Now play the game. You’ll discover that the result is the same. The alien falls through the floor. Why is this happening?

Adding a mesh collider

When using gravity, GameObject will fall into the abyss unless two things are met. A GameObject must have a collider on it and it must be placed on another GameObject with a collider. In the case of your alien, it does have a collider, but the arena does not.

As mentioned, there are many colliders at your disposal and you’re not restricted to just one. Any GameObject may have multiple colliders, giving you the ability to create complex shapes and reactions to collisions.

You could add a bunch of colliders to the arena to approximate its shape, but the arena is quite complicated and that would take a lot of work. So, in this case, you’ll use a mesh collider instead.

A mesh collider creates the collider boundaries from an actual mesh object, i.e., the geometry used to create the model. It’s a great option when you have a complicated model. The problem with mesh colliders is they can be “expensive” — it takes a lot of resources to maintain the collider and determine if it’s involved in collisions. In such cases, it helps to have a very low-poly collider.

To create a low-poly collider, you just take the original model and strip it of extraneous detail until you’re down to the shape. Mike Berg, the artist for Bobblehead Wars, has done that for you.

In the Hierarchy, expand the BobbleArena GameObject and select the World Centre GameObject. In the Inspector, click the Add Component button. Select Physics, and in the component listing, click Mesh Collider.

This shows the mesh collider component.

Find the BobbleArena-Collider in the Models folder, expand it by clicking the disclosure triangle, and then drag the Inner_Octagon mesh to the collider’s Mesh property.

In this screenshot, the user is dragging the inner octogon into the mesh collider.

Initially, the mesh is a little too large and misaligned.

This shows the area with an oversized collider.

In the transform component, set the Rotation to (-89.98, 0, -22.26) and the Scale to (0.949, 0.949, 0.949). The collider will now match the arena.

This shows the properly alligned collider.

Play your game! Unfortunately for the hero, the bug no longer falls through the floor.

An evil alien celebrates being able to stand on the floor.

Blast that bugger away! You’ll notice that the alien responds to collisions and gets knocked. Things are getting interesting.

Where to go from here

Colliders are a key component of working with Unity. These colliders add for hit detection but they also allow GameObject to resist the pull of gravity. One thing not covered in this series is gravity itself. It is designed to act like Earth’s gravity. That is, the world is applying -9.81 units of force in the Y axis. You can change this by clicking Edit > Project Settings, then selecting the Physics category.

You can learn more about the Physics category by visiting Unity’s official documentation.

Your next step is to upgrade the marine. You’ve been using your own character controller, but Unity provides one out of the box. You’ll implement this in the next tutorial.


Discover more from Jezner Blog

Subscribe to get the latest posts sent to your email.

By Brian Moakley

Brian Moakley is a writer and editor who lives amongst the quiet hills in New England. When not reading tales of high adventure, he is often telling such stories to all who will listen.

Related Post

Leave a Reply