Unity InputSystem actual combat (1)

UnityInputSystem series directory

Unity InputSystem actual combat (1)
Unity InputSystem actual combat (2)

Article directory

  • UnityInputSystem series catalog
      • foreword
      • installation method
      • InputActionsCreate
      • InputActions settings
      • Code calls InputAction
      • The old version of the code controls the character to move up, down, left, and right
      • The new version of the code controls the character to move up, down, left, and right
      • animation
      • skills

Foreword

This article is based on Unity2023.1.0a26 version: version 1.5 official website address
The new version of the input system launched by Unity, the old version of the input system is likely to be abandoned, so hurry up and learn it

NOTE: The new input system requires Unity 2019.4+ and the .NET 4 runtime. It doesn’t work in projects using the old .NET 3.5 runtime

Installation method

  • Open Windows > Package Manager

  • In the opened interface, find InputSystem and click Install. I have installed it here

  • If the interface pops up, select Yes to enable the new input system

  • In the future, you can also find the Active Input Handling option in Edit > Project Settings > Player, and choose to use the old version of the input system or the new version of the input system, or both

InputActions creation

  • Right-click Create > Input Actions in the Project panel, and an inputactions file will be generated, named GameControls

  • Then check the automatic generation script in the corresponding Inspector panel

  • You can see that the GameControls.cs script is generated in the same directory

InputActions settings

  • Next double click on the GameControls.inputactions configuration file

  • In the opened interface, we create an ActionMaps named Player

  • We implement an Action that controls the player to move up, down, left, and right

  • First rename Action to Move, then modify ActionType to Value, then ControlType >For Vector2

  • Why is it set up like this? You can find that there are three types of ActionType. According to the general description, we can know that we need continuous input, and the movement needs to obtain a Vector2 type parameter (x, y)

Value is mainly used for input with continuous state changes, such as mouse movement, remote sensing of handles. If there are multiple devices bound to this Action, only the input from one of the devices (the most controlled) will be sent
Button The Action used to be triggered every time it is pressed
Pass-Through is the same as Value, the difference is that if there are multiple devices bound This Action will send input from all devices
  • Next, we right click on the Move Action to add bindings and create a 2D Vector

  • Here are the meanings of these bindings

binding Add binding device operation to Action
Add Binding Ordinary binding, you can bind a button, cursor, joystick, etc.
Add Up\Down\Left\Right Composite The combination of four buttons, the return value is Vector2, such as WASD
Add Binding With One Modifier need to press two buttons at the same time Combinations such as ctrl + 1
Add Bingding With Two Modifiers A combination that requires pressing three buttons at the same time such as shift + ctrl + 1
  • Then we need to add button binding WASD for up, down, left, and right i2.wp.com/img-blog.csdnimg.cn/img_convert/98d5ce8578bf47830b96f8ffe2836d29.png” alt=””>

  • Now we have added the PC keyboard input

  • Next, we can add the joystick input of the mobile terminal, select the Binding that we have been ignoring just now, and set the path to the left joystick

  • The settings related to the mobile terminal are complete. We have set up two platforms. Later, you can freely configure the desired platform according to the situation.

Code calls InputAction

  • Recommend a more comfortable way for me to use
  • Create the code InputManager.cs
using UnityEngine;

public class InputManager : MonoBehaviour
{
    public static GameControls gameControls { get; private set; }

    private void OnEnable()
    {
        if (gameControls == null)
            gameControls = new GameControls();

        gameControls. Enable();
    }

    private void OnDisable()
    {
        if (gameControls != null)
            gameControls. Disable();
    }
}
  • The very simple code is enough for all our subsequent usage methods, and then I will give you a practical test

The old code controls the character to move up, down, left, and right

using UnityEngine;

public class Player : MonoBehaviour
{
    [Header("The protagonist's speed")]
    public float moveSpeed;

    private Rigidbody2D playerRB;

    // cache movement direction
    private float input_X;
    private float input_Y;
    private Vector2 input_MoveDir;

    private void Awake()
    {
        playerRB = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        PlayerInput();
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void PlayerInput()
    {
        input_X = Input. GetAxisRaw("Horizontal");
        input_Y = Input. GetAxisRaw("Vertical");
        if (input_X != 0 & amp; & amp; input_Y != 0)
        {
            input_X = input_X * 0.7f;
            input_Y = input_Y * 0.7f;
        }
        input_MoveDir = new Vector2(input_X, input_Y);
    }

    private void Move()
    {
        playerRB.MovePosition(playerRB.position + input_MoveDir * moveSpeed * Time.deltaTime);
    }
}

The new code controls the character to move up, down, left, and right

  • First, create an empty object on the scene and mount the InputManager on it

  • Next, look at the official description of Action callbacks: Each Action has a set of different stages that it can go through when receiving input

Phase Description
Disabled The operation is disabled and cannot receive input
Waiting The operation is enabled and is actively waiting for input
Started The input system has received an input that initiated the interaction with the action
Performed The interaction with the action has been completed and Continuous monitoring
Canceled The interaction with the operation has been canceled
  • upper code
using UnityEngine;

public class Player : MonoBehaviour
{
    [Header("The protagonist's speed")]
    public float moveSpeed;

    private Rigidbody2D playerRB;

    // cache movement direction
    private float input_X;
    private float input_Y;
    private Vector2 input_MoveDir;

    private void Awake()
    {
        playerRB = GetComponent<Rigidbody2D>();
    }

    void Start()
    {
        InputManager.gameControls.Player.Move.performed += OnMovePerformed;
    }

    private void OnDisable()
    {
        InputManager.gameControls.Player.Move.performed -= OnMovePerformed;
    }

    private void OnMovePerformed(UnityEngine. InputSystem. InputAction. CallbackContext obj)
    {
        Vector2 moveDir = obj. ReadValue<Vector2>();
        input_X = moveDir.x;
        input_Y = moveDir.y;
        if (input_X != 0 & amp; & amp; input_Y != 0)
        {
            input_X = input_X * 0.7f;
            input_Y = input_Y * 0.7f;
        }
        input_MoveDir = new Vector2(input_X, input_Y);
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void Move()
    {
        playerRB.MovePosition(playerRB.position + input_MoveDir * moveSpeed * Time.deltaTime);
    }
}
  • Is it very simple to use, so that the computer can control the characters to move up, down, left, and right
  • Then someone will ask, InputSystem is not difficult to use, but where are the benefits? The advantage of course is that only this set of code is needed to adapt to multiple platforms. The next article will lead you to realize how to realize mobile phone mobile without changing the code (spoiler: create a joystick UI and mount a script)
  • Of course, you can’t imagine the InputSystem too simple, because if you work with me step by step, you can find that the characters can move, but they can’t stop. It’s very simple. We just need to monitor and cancel the interface.
  • upper code
using System;
using UnityEngine;

public class Player : MonoBehaviour
{
    [Header("The protagonist's speed")]
    public float moveSpeed;

    private Rigidbody2D playerRB;

    // cache movement direction
    private float input_X;
    private float input_Y;
    private Vector2 input_MoveDir;

    private void Awake()
    {
        playerRB = GetComponent<Rigidbody2D>();
    }

    void Start()
    {
        InputManager.gameControls.Player.Move.performed += OnMovePerformed;
        InputManager.gameControls.Player.Move.canceled += OnMoveCanceled;
    }

    private void OnDisable()
    {
        InputManager.gameControls.Player.Move.performed -= OnMovePerformed;
        InputManager.gameControls.Player.Move.canceled -= OnMoveCanceled;
    }

    private void OnMovePerformed(UnityEngine. InputSystem. InputAction. CallbackContext obj)
    {
        Vector2 moveDir = obj. ReadValue<Vector2>();
        input_X = moveDir.x;
        input_Y = moveDir.y;
        if (input_X != 0 & amp; & amp; input_Y != 0)
        {
            input_X = input_X * 0.7f;
            input_Y = input_Y * 0.7f;
        }
        input_MoveDir = new Vector2(input_X, input_Y);
    }

    private void OnMoveCanceled(UnityEngine.InputSystem.InputAction.CallbackContext obj)
    {
        input_X = 0;
        input_Y = 0;
        input_MoveDir = Vector2.zero;
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void Move()
    {
        playerRB.MovePosition(playerRB.position + input_MoveDir * moveSpeed * Time.deltaTime);
    }
}

Animated presentation

Please add a picture description

Tips

  • Get all current touches from the touchscreen
 using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;
    private void Update()
    {
        foreach (var touch in Touch. activeTouches)
            Debug.Log($"{touch.touchId}: {touch.screenPosition},{touch.phase}");
    }
  • You must first enable enhanced touch support by calling InputSystem.EnhancedTouch.Enable() .
  • You can also use the lower-level Touchscreen.current.touches API.