Taking Control of Gravity on Unity3D

One of the most fun things to play with in Unity is gravity. Even when things go wrong, it’s more than amusing to see the effects cause by failure. I would go as far as saying that, at times, I’ve wanted something to go wrong just to add that bit extra spice to the day. Anyway, let’s look at creating a simple scene in Unity, using some simple objects, in which we’ll look at how to make use of, and control gravity.

For this article, I’m using Unity version 5.6.0f3 Personal. And, for editing C# scripts, I’ll be using Visual Studio 2017. However, anything that can be used to edit a C# file will be fine for scripts.

You can download both via the following links…

Once downloaded, if you don’t have them installed yet, you may be asked to update the Visual Studio plug-in for Unity3D. It doesn’t take long to install. Once you’re ready, we can begin.

Creating the Scene

The scene we’ll be using is a very basic one. There’ll be four game objects; the first two will be there by default. These are the camera and a directional light. The second two we’ll add; but, before we do that, let’s create that scene.

Starting up Unity3D, we’re presented with a dialogue box that looks like Figure 1.

The dialogue box shown on start-up
Figure 1: The dialogue box shown on start-up

Using the ‘NEW’ button underlined in red, create yourself a new project. You then will be presented with this screen…

Setting up the new project
Figure 2: Setting up the new project

Be sure to select ‘3D’ for the project type, and of course choose a location of your choice. You can enable or disable analytics at your discretion, but we won’t be doing anything with analytics during this article.

Create the project, and you’ll arrive at the place where we can dig in and start doing stuff with our scene. On starting a new project, we can see something like what we see in Figure 3…

The newly created scene, which has been saved and named 'Scene One'
Figure 3: The newly created scene, which has been saved and named ‘Scene One’

Looking at the hierarchy panel, which is identified by the red line in Figure 3, we can see we have the two objects we mentioned earlier. These two objects are fundamental to the scene, so don’t delete them. Now, let’s add our two custom objects.

Creating a Plane object
Figure 4: Creating a Plane object

Using Figure 4 as a guide, right-click the hierarchy panel and create a Plane object, as show. Then, do the same and create a Cube.

If everything went to plan, we’ll have a scene that now looks like this…

The scene with a newly created Cube and Plane objects
Figure 5: The scene with a newly created Cube and Plane objects

The cube, however, is a little low, because we want this to appear above the Plane. The idea is that the Cube will fall under the effect of gravity, and the Plane will catch the cube. So, first, let’s raise that cube a little. Using the mouse, grab hold of the yellow arrow pointing upwards, and drag it up.

The Cube raised above the Plane
Figure 6: The Cube raised above the Plane

Now, both objects by default should have colliders added to their object tree; this can be viewed by selecting an object and opening the inspector panel on the right-hand side of the environment. But, if we were to play the scene now, using the play button shown at the top of Figure 6, we would see the game objects just remain static in our scene.

What we need to do is add the Rigidbody component to our cube. Using Figure 7 to guide you, select the cube and press the ‘Add Component’ button on the inspector.

The add component drop-down on the inspector panel
Figure 7: The add component drop-down on the inspector panel

If you can’t see the Rigidbody component on opening the ‘Add Component’ drop-down, you can find it under Physics. Once done, simple start your scene again by using the play button and observe the results.

By default, Rigidbody has ‘Use Gravity’ enabled. That, and working with the colliders added by default to your 3D objects, enabled the Plane to catch the falling Cube, and stop it from leaving the scene.

The scene in play more, showing the Cube caught by the Plane
Figure 8: The scene in play more, showing the Cube caught by the Plane

Adding a Little C#

Now we have our scene, and gravity is visible working. Let’s now add a little code to do something with our scene at runtime.

Right-click the Assets panel, which by default is at the bottom of your environment. Click Create -> C# Script (see Figure 9).

A C# script added to our assets
Figure 9: A C# script added to our assets

Name the file anything you like; its name isn’t important for this demonstration. However, before we edit the code, drag and drop the script on to the Main Camera object show on the hierarchy view. Because the camera is present through the life time of the scene, it’s a good place to run scripts from. And, simply dragging and dropping the script onto a game object will bring that script into play during runtime.

Now, let’s look at some code. Opening the script, my code looks like this…

public class GravityControl : MonoBehaviour {

   GameObject _plane;
   // Use this for initialization
   void Start () {
      _plane = GameObject.Find("Plane");
   }

   // Update is called once per frame
   void Update () {

      if (Input.GetKey(KeyCode.DownArrow))
      {
         _plane.transform.Translate(Vector3.down *
            Time.deltaTime);
      }
      if (Input.GetKey(KeyCode.UpArrow))
      {
         _plane.transform.Translate(Vector3.up *
            Time.deltaTime);
      }

   }
}

At the top of our class, we can declare a field which we’ll use to keep a reference to the Plane object. Then, as the Start method is called, which will happen at the start of the scene, we can use GameObject.Find(“Plane”) to get that object.

Next, in the Update() method, we are going to look for the down arrow and up arrows on the keyboard being held down. And, on either being held, we’ll move the Plane accordingly. Once you’ve entered your code, save your script and run the scene again.

This time, you should be able to move the Plane up or down, and push or allow the cube to fall, depending on which way you move the Plane.

Conclusion

What we’ve talked about in this article is a very simple getting started guide to gravity; but, from this article, I would recommend experimenting with what else you can do in C# to control your scene. Could you place another object that then pushed your cube off the end of the Plane? Even have a series of objects to then catch it as it falls. How about using a sphere and creating a track for it to roll down? As I said at the start, there’s quite a lot of fun to be had with just what we’ve seen here today.

If you have any questions, please tweet me on Twitter @GLanata.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read