Player Controls (New Input System)

Character Controller 3D Project

You don’t have access to this lesson
Please register or sign in to access the course content.

In this lesson you will create a Character Controller using Unity.

This project assumes that you have a player object with a Character Controller added with the new input system. There is a zip file download attached to this lesson which you can download and use.

In Unity select the Player Objects and click add component in the Inspector.

Add a Character Controller

Create a new PlayerController Script as shown below.

  • Line 4 includes the InputSystem for the new input system.
  • Line 8 contains the variable for storing the 2D vector for the user input for movement.
  • Line 9 is a variable for the CharacterController Object
  • Line 13 assigns the CharacterController of the player object to the variable cc made on Line 9. This is placed inside the Start() method so that it will be run when the object is instantiated (created).
  • Lines 16-20 involve creating the OnMove() method. This method takes a parameter of the type InputValue, this parameter is called iv for input value.
  • We use On and then the name of the binding that is set in the input actions created for the player. In this case OnMove. You can create custom Bindings. Find out how here.
  • Line 18 is a Debug message which can be removed. This is to check that the OnMove event is triggered.
  • Line 19 creates assigns data to the movementInputVector variable created on Line 2.
  • The code iv.Get<Vector2>(); takes the InputVector parameter and get the 2D vector (with x and y) coordinates for how the input has been pressed.
  • Lines 23-26 are a FixedUpdate() method that will run a fixed number of times each second.
  • On line 25 we use the SinpleMove() method the the character controller (cc) to move the player object.
  • On this method we create a new 3D vector (Vector3) that takes the x and y coordinates of the movementInputVector variable.
  • Note that we pass values to the x and z values and these are the horizontal and depth axes in 3D environments. We leave the y axis at 0 as we are not changing the height here.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerControllerCharacterController : MonoBehaviour
{
    Vector2 movementInputVector;
    CharacterController cc;
    // Start is called before the first frame update
    void Start()
    {
        cc = GetComponent<CharacterController>();
    }

    void OnMove(InputValue iv)
    {
        Debug.Log("Move");
        movementInputVector = iv.Get<Vector2>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        cc.SimpleMove(new Vector3(movementInputVector.x, 0.0f, movementInputVector.y));
    }
}