In this section, we will cover the basics of handling user input in Unity. Understanding how to capture and respond to user input is crucial for creating interactive and engaging games. We will explore how to use Unity's Input system to detect key presses, mouse movements, and other forms of input.

Key Concepts

  1. Input Class: Unity's built-in class for handling input.
  2. Detecting Key Presses: How to check if a key is pressed or held down.
  3. Mouse Input: Capturing mouse movements and clicks.
  4. Axis Input: Using Unity's input axes for smoother control.

Input Class

Unity provides the Input class to handle various forms of input. This class includes methods and properties to detect key presses, mouse movements, and other input events.

Common Methods in the Input Class

  • Input.GetKey(KeyCode key): Returns true while the specified key is held down.
  • Input.GetKeyDown(KeyCode key): Returns true during the frame the user starts pressing the specified key.
  • Input.GetKeyUp(KeyCode key): Returns true during the frame the user releases the specified key.
  • Input.GetMouseButton(int button): Returns true while the specified mouse button is held down.
  • Input.GetMouseButtonDown(int button): Returns true during the frame the user starts pressing the specified mouse button.
  • Input.GetMouseButtonUp(int button): Returns true during the frame the user releases the specified mouse button.
  • Input.GetAxis(string axisName): Returns the value of the virtual axis identified by axisName.

Detecting Key Presses

Let's start by detecting key presses. We'll create a simple script that moves a GameObject when the arrow keys are pressed.

Example: Moving a GameObject with Arrow Keys

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 5.0f;

    void Update()
    {
        Vector3 move = new Vector3();

        if (Input.GetKey(KeyCode.UpArrow))
        {
            move += Vector3.forward;
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            move += Vector3.back;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            move += Vector3.left;
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            move += Vector3.right;
        }

        transform.Translate(move * speed * Time.deltaTime);
    }
}

Explanation

  • Vector3: Represents a 3D vector. We use it to store the movement direction.
  • Input.GetKey: Checks if a specific key is held down.
  • transform.Translate: Moves the GameObject in the specified direction.

Mouse Input

Next, we'll handle mouse input. We'll create a script that rotates a GameObject based on mouse movement.

Example: Rotating a GameObject with Mouse Movement

using UnityEngine;

public class MouseLook : MonoBehaviour
{
    public float sensitivity = 100.0f;
    private float rotationX = 0.0f;
    private float rotationY = 0.0f;

    void Update()
    {
        rotationX += Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
        rotationY -= Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;

        rotationY = Mathf.Clamp(rotationY, -90.0f, 90.0f);

        transform.localRotation = Quaternion.Euler(rotationY, rotationX, 0.0f);
    }
}

Explanation

  • Input.GetAxis("Mouse X"): Gets the horizontal mouse movement.
  • Input.GetAxis("Mouse Y"): Gets the vertical mouse movement.
  • Mathf.Clamp: Clamps a value between a minimum and maximum value.
  • Quaternion.Euler: Creates a rotation from Euler angles.

Axis Input

Unity's input axes provide a way to handle input more smoothly. By default, Unity includes axes for horizontal and vertical movement, which can be accessed using Input.GetAxis.

Example: Moving a GameObject with Axis Input

using UnityEngine;

public class PlayerMovementAxis : MonoBehaviour
{
    public float speed = 5.0f;

    void Update()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 move = new Vector3(moveHorizontal, 0.0f, moveVertical);

        transform.Translate(move * speed * Time.deltaTime);
    }
}

Explanation

  • Input.GetAxis("Horizontal"): Gets the horizontal axis value.
  • Input.GetAxis("Vertical"): Gets the vertical axis value.
  • Vector3: Stores the movement direction.
  • transform.Translate: Moves the GameObject in the specified direction.

Practical Exercise

Task

Create a script that allows a GameObject to jump when the spacebar is pressed. The GameObject should only be able to jump if it is on the ground.

Solution

using UnityEngine;

public class PlayerJump : MonoBehaviour
{
    public float jumpForce = 5.0f;
    private bool isGrounded;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            isGrounded = false;
        }
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }
}

Explanation

  • Input.GetKeyDown(KeyCode.Space): Checks if the spacebar is pressed.
  • GetComponent().AddForce: Applies a force to the Rigidbody to make the GameObject jump.
  • OnCollisionEnter: Detects when the GameObject collides with another object.
  • isGrounded: A boolean to check if the GameObject is on the ground.

Summary

In this section, we covered the basics of handling input in Unity. We learned how to:

  • Use the Input class to detect key presses and mouse movements.
  • Move and rotate GameObjects based on user input.
  • Use Unity's input axes for smoother control.

Understanding these concepts is essential for creating interactive games. In the next module, we will dive deeper into working with assets in Unity.

© Copyright 2024. All rights reserved