Handling User Input and Physics

Tutorial 4 of 5

1. Introduction

Welcome to this Unity tutorial that aims to teach you how you can handle user input and implement physics in your Unity-based game.

In this tutorial, you'll learn how to:
* Detect keyboard and mouse input from a user
* Apply physics to game objects in Unity, making them move, collide, and interact in realistic ways.

Before we begin, it's recommended that you have a basic understanding of:
* Unity environment
* C# programming language
* Basic game design concepts

2. Step-by-Step Guide

2.1 Handling User Input

User input in Unity can be captured via the Input class. The Input class has several methods to detect different kinds of input, such as key presses, mouse movement, etc.

For example, to check if the player has pressed the 'W' key, we use:

if (Input.GetKey(KeyCode.W))
{
    // Execute your code here
}

2.2 Implementing Physics

Unity's physics system is used to simulate realistic interactions between objects. This system is built upon the NVIDIA PhysX engine.

To make an object obey the laws of physics, you need to add a Rigidbody component to it. Rigidbody includes properties like mass, drag, and gravity.

To apply a force to an object, we can use the AddForce() method, like so:

Rigidbody rb = GetComponent<Rigidbody>();
rb.AddForce(Vector3.forward * 10);

3. Code Examples

3.1 Detecting User Input

void Update()
{
    if (Input.GetKey(KeyCode.W))
    {
        Debug.Log("W key is being pressed");
    }
}

This code will print "W key is being pressed" in the console when the 'W' key is being held down.

3.2 Applying Physics

public class PhysicsObject : MonoBehaviour
{
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            rb.AddForce(Vector3.up * 10);
        }
    }
}

In this code, when the space bar is pressed, a force is applied to the object in the upward direction, causing it to move.

4. Summary

In this tutorial, we learned how to handle user input and implement physics in Unity. We learned how to use the Input class to detect keyboard input, and how to use the Rigidbody component to apply physics to game objects.

Next, you may want to learn how to handle more complex inputs, like gamepad input or touch input. You can also delve deeper into the physics engine, learning how to apply torque, handle collisions, and more.

5. Practice Exercises

5.1 Exercise 1

Create a cube that moves forward when the 'W' key is pressed.

5.2 Exercise 2

Make the cube from Exercise 1 jump when the 'Space' key is pressed.

5.3 Exercise 3

Create a simulation where two cubes collide and react to each other's force.

Remember, practice is key to mastering these concepts. Happy coding!