Home Game Tech Books Unity Apprentice

6
Input & Collisions Written by Eric Van de Kerckhove

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

In the last chapter, you learned how to add a camera to the scene and set it up. You also mastered the art of using lighting and shadows to make the scene look great. In this chapter, you’ll learn about Unity’s input systems and how to use them to make the player avatar walk around.

Besides reading and using the player’s input, you’ll also discover how to use Unity’s physics system to make sure objects can’t fall through the floor. The combination of an input system and a physics system is the foundation for a lot of games out there. For example, it allows an avatar to run around on platforms, jump and bonk enemies on their heads.

Even real-world games like Jenga use a combination of the player’s dexterity and gravity to create fun gameplay! Once you’ve mastered the concepts in this chapter, you’ll be ready to create quite a few fun projects of your own.

Input systems

To get started, open the starter project for this chapter in Unity. If it wasn’t opened automatically, open the DiningHall scene located in RW / Scenes. You’ll see the familiar scene from the last chapter: a dining hall full of gladiators spreading their arms wide.

Before diving into setting up the input system, you need to understand what an input system is and what choices Unity offers.

The old code way

This might be glaringly obvious, but every game needs input from the player. Whether it’s a button press, the movement of a mouse or the swipe of a finger on a touchscreen, input is essential for games. In Unity, there are a few ways to go about capturing a player’s input — one of which is simply calling the Input class in a script like this:

void Update() 
{ 
    if (Input.GetKeyDown(KeyCode.Space)) 
    { 
        Jump();
    } 
}

Old input system

Of course, that’s only one way of going about polling for the player’s input. Unity comes with two input systems — the old one and the new one. The old input system is still the default and has been since the first release of Unity way back in 2005. Time for a small history lesson!

void Update() 
{ 
    if (Input.GetButtonDown("Jump")) 
    { 
        Jump();
    } 
}

New input system

This is where the new input system comes into play! This system has been in development since 2018 and has been officially out of preview since 2021. It’s now a built-in part of Unity and is much more intuitive once you get the hang of it. It features cross-platform compatibility, the ability to remap controls at runtime, an input debugger and it binds actions to controls. Pretty sweet!

Setting up the new input system

The first step to switching over to the new input system is opening the Project Settings by navigating to Edit ▸ Project Settings…. Now select Player at the left-hand side to open the Player settings.

Input actions

Now the new input system is activated, you’ll need to create an Input Actions file to map the player input to actions. To do this, first create a new folder in the RW folder named Input.


Control schemes

First, you’ll need to add control schemes. These are the physical devices you want to support, like keyboards, gamepads, touchscreens and even accelerometers.

Action maps

Now that you’ve decided on the input methods, the next step is to create an action map. This is a set of actions that are related to each other in some way. For example, take a game that has the player avatar walking on foot, but also occasionally riding on horseback.

Actions

An action is something that can be done in-game that needs to be linked to the player’s input. This can be a jumping, shooting, moving, whistling, etc. You need an action for just about anything an avatar can do so the player can perform it.

Bindings

A binding is the player’s input, like button presses, the state of a joystick or even the movement of a VR controller. This is what connects an action to the physical world.

M Y E M R N 5 3 -5 -2 P A H Y

Linking input to movement

An Input Actions asset by itself isn’t enough to poll for the player’s input. For that, you’ll need to add a Player Input component.

Player Input component

This component uses an Input Actions file as its input, checks for any triggered actions and can pass the results along to a script. Click on the circular selection button next to the Actions property and select the Input Input Actions file you created earlier. Doing so adds some extra properties below Actions. Here’s what these are for:

Character Controller component

At this point, you can take the player’s input and use it in any way you want. To get the avatar moving through the scene, you’ll need a component that handles the avatar’s movement without moving through the floor or walls. You could script this yourself, but Unity comes with a handy component built-in: a Character Controller. Add one to the Player Avatar by clicking the Add Component button at the bottom of the Inspector, searching for “Character” and selecting Character Controller in the list.

Scripting the movement

Time for some scripting! To start, the movement input should be processed and passed to the Character Controller. Create a new folder in RW / Scripts and name it Player. Right-click inside this folder, select Create ▸ C# Script and name the script PlayerAvatar.

using UnityEngine.InputSystem;
public float movementSpeed = 5f; // 1
public float rotationSpeed = 10f; // 2
public float gravity = 20f; // 3
public Animator animator; // 4

private CharacterController characterController; // 5
private Vector2 movementInput = Vector2.zero; // 6
private bool allowInput = true; // 7
characterController = GetComponent<CharacterController>();
public void Move(InputAction.CallbackContext context) // 1
{
    if (!allowInput) // 2
    {
        return;
    }

    movementInput = context.ReadValue<Vector2>(); // 3
}
private void UpdateMovementAndRotation()
{
    // 1
    Vector3 movementVector = new Vector3(-movementInput.y, 0, movementInput.x);
    // 2
    characterController.Move(movementVector * movementSpeed * Time.deltaTime);
    // 3
    transform.rotation =
        Quaternion.Slerp(transform.rotation,
                         Quaternion.LookRotation(movementVector),
                         Time.deltaTime * rotationSpeed);
}

private void UpdateGravity()
{
    characterController.Move(Vector3.down * gravity * Time.deltaTime);
}
if (movementInput != Vector2.zero && allowInput) // 1
{
    UpdateMovementAndRotation(); // 2
    animator.SetFloat("Speed", 1f); // 3
}
else // 4
{
    movementInput = Vector2.zero;
    animator.SetFloat("Speed", 0f);
}

UpdateGravity(); // 5

Physics

Now that you can move the character around, you might have noticed you can move through the tables and the NPCs. While the scene comes with the colliders needed for the geometry, no colliders have been added for most props. Select Colliders in the Hierarchy and take a look at the scene view. All of the green boxes you see around the scene are box colliders that have been set up for the geometry.

Key points

  • Unity comes with two input systems: the old one and the new one. The former is enabled by default.
  • You can enable the new input system via Edit ▸ Project Settings… ▸ Player.
  • To start mapping controls to actions, you need to create an Input Actions file.
  • A control scheme is a collection of physical devices like keyboards and gamepads.
  • An action map is a set of actions that are related to each other in some way.
  • An action is something that can be done in-game that needs to be linked to the player’s input.
  • A binding is the player’s input. It connects an action to the physical world.
  • A composite allows for multiple input bindings that result in one final output value.
  • To use the Input Actions file and poll for input, you need a Player Input component.
  • Events get called when input actions are triggered. These events can call functions, which can change properties of components and/or call methods.
  • A Character Controller is a simple component for moving an avatar around a scene. Its Move method needs to be called from a script.
  • Colliders are simple 3D shapes that represent their high-resolution counterparts. Some examples include boxes, spheres and capsules.
  • A collider component automatically adjusts its size when a Mesh Renderer component is also attached to the same GameObject.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

© 2022 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.