Capturing User Input in Unity3D to Change Behavior/Movement

Although it isn’t important to the content of this article, you may—or may not—have been following along with my series of Unity3d articles. In these articles, we covered creating a scene, animation, gravity, and building a UWP application from Unity3D.

Reading the previous articles isn’t necessary to follow this article; however, what you’ll learn here will round up those lessons quite nicely. Today, you’ll look at building a small scene where the elements react to each other in small ways. This interaction will limited for the scope of this article, but the technique used to achieve that interaction will be of great use when expanding your own game.

Building the Unity3D Scene

Start Unity3D. If you don’t have Unity3D, you can download a copy from its Web site.

Note: You will need to create an account if you don’t have one already. For this article, I’m using Visual Studio 2017 for code editing.

Once started, create an empty 3D project, and give it a useful name:

The Unity3D Create project dialogue
Figure 1: The Unity3D Create project dialogue

Be sure to select ‘3D,’ and click the Create project button.

Before looking at adding the elements and scripts to the example scene, it is worth taking a look at the finished product. Figure 2 shows the main view port Plane with two spheres and a camera.

The Unity3D scene as shown once created
Figure 2: The Unity3D scene as shown once created

In the image, you can see the camera’s field of view indicated by the thin lines coming from the camera. If you select the camera, you’ll also see what the camera sees via the preview window at the bottom right of the scene view.

The camera preview window (visible when the camera is selected)
Figure 3: The camera preview window (visible when the camera is selected)

What this camera sees here is very important. It’s what the user will see when the game is running.

There are a number of actions that will occur when the scene shown in Figure 2 is complete. Clicking the left mouse button on the sphere closest to the camera will send it towards the second sphere. The second sphere, using an attached script of its own, will do something when hit by the first sphere.

For this article, the second sphere will be destroyed when the first collides with it. However, a Plane will need to be added so the spheres don’t fall off the bottom of the scene when the game is played.

To add the Plane, select 3D Object→Plane from the GameObjects menu. (In Unity 4, this would be from the Create Object→Plane from the GameObjects menu.)

Adding a Plane to our scene
Figure 4: Adding a Plane to our scene

Once the Plane is created, go ahead and create two spheres, which will need to be positioned. If you look at Figure 5, you’ll see the settings I’ve entered for the first sphere.

Sphere One's starting position
Figure 5: Sphere One’s starting position

The settings for the second sphere, which I have renamed to ‘TargetSphere,’ are show in Figure 6.

TargetSphere's position settings
Figure 6: TargetSphere’s position settings

If you run the scene at this point, you should see the two spheres from the camera’s field of view, but they will not fall due to the gap between them and the Plane below. This is because we need to add a component named ‘Rigidbody’ to each of the spheres. It is this component that will deal with gravity and enable movement later in this article.

To do this, select a sphere—be sure to have the Inspector tab open—and click add component, then physics, and then Rigidbody. Please use Figure 7 as a reference.

Adding a 'Rigidbody' to your selected sphere
Figure 7: Adding a ‘Rigidbody’ to your selected sphere

Do the same for the other sphere.

You may have noticed in Figure 2 that there are two scripts in the scene showing on the assets panel.

The two game scripts
Figure 8: The two game scripts

These two scripts will contain the code to push the first sphere, and add behaviour to the second, ‘Target,’ sphere. To add a script, right-click the assets panel and click Create, then C# Script. I’ve named my two scripts ‘GameScript’ and ‘TargetBehaviourScript.’ The first will be attached to the camera, and the second to the sphere that will be hit; this will be covered in a moment.

Firstly, look at the code in these scripts. The ‘GameScript’ code looks like this:

public class GameScript : MonoBehaviour {

   public float force = 5f;

   // Use this for initialization
   void Start ()
   {

   }

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

      if (Input.GetMouseButtonUp(0))
      {
         Ray ray = Camera.main.ScreenPointToRay
               (Input.mousePosition);
            RaycastHit hit;

         if (Physics.Raycast(ray, out hit))
         {
            if (hit.collider.name == "Sphere")
            {
               var sphere = hit.collider.gameObject;
               sphere.GetComponent<Rigidbody>().AddForce
                  (new Vector3(0.0f, 0.0f, force),
                   ForceMode.VelocityChange);

            }
         }
      }
   }
}

In this script, which will be attached to the camera, the mouse button 0 (which is usually the left button) is being watched for a press. When it’s been pressed, a ray is drawn from the point of the click through the game scene. From this ray, you want to detect if any colliders are hit; specifically, you are looking for the collider attached to the first sphere, named ‘Sphere,’ being hit by the ray.

If it’s been hit, you know it was the first sphere hit by the click and now you can add some force to make it move across the Plane. For this article, the sphere will only move in one direction. You should be able to work out how to make the sphere travel along the direction of the click in your own good time.

Moving on, look at the code that is to be attached to the second Sphere. It looks something like the following:

public class TargetBehaviourScript : MonoBehaviour
{

   // Use this for initialization
   void Start()
   {

   }

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

   }

   void OnCollisionEnter(Collision collision)
   {
      if (collision.collider.name == "Sphere")
      {
         DestroyObject(this.gameObject);
      }
   }

}

Because 3D objects have a collider added to the component out of the box (by default); you can make use of the OnCollsionEnter to method, which has passed into it the collision object from which you can work out what collided with the object the script is attached to. Then, all you have to do is check to see if it was the first sphere that collided with this second sphere, and then destroy the second sphere if the check comes back as true.

If all has gone according to plan, you now have the code needed to make this scene work. Next, attach the scripts to their respective components. You can use Figure 9 as a reference to do that now.

Attaching a script to a component
Figure 9: Attaching a script to a component

Looking at 1 on Figure 9, drag the ‘GameScript’ to the main camera, indicated by 2. If the action was successful, and you select the camera, you’ll see the script on the list of components added to the object indicated by 3.

Do the same with the ‘TargetBehaviourScript,’ but this time attach it to the ‘TargetSphere.’

And, that’s it! Run the game by pressing the play button found at the top of the Unity desktop; click the first sphere and observe the results.

The game in play mode after the first sphere was clicked
Figure 10: The game in play mode after the first sphere was clicked

Conclusion

What you’ve seen in this article is a very simple implementation of cause and effect. You have a sphere which strikes another, causing it to disappear. Although this is very simple, this is the basis of much of the behaviour you might see in a game; it is enough to open a world of interaction within your own scene.

If you have any questions, you can always find me on Twitter @GLanata

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read