New Input System - 2D Move

I keep looking up how to move the character using the new input system for 2D using "Invoke Unity Events." This is what my successful setup looks like.

Creating Input Actions

Right click in the project folder and then go to "Create" -> Input Actions

Player GameObject

This has four components. I've opted to put the sprite rendered on a child game object of this because of a shielding function later.

The components needed here are:

  • Collider2D - Anyone will do

  • Rigidbody 2D

  • Player Input

  • Custom script to control the player gameobject, named here "Player Controller"

Note: For the "Collision Detection" property, set it to "Continuous" or the camera gets shaky.

Invoke Unity Events

Because we're going to be "Behavior: Invoke Unity Events," you do not need the following code.

This method is more performant than "Broadcast Messages" because this will only trigger once the input is interacted with rather than sending it every frame.

private void Awake() {
playerInput = GetComponent<PlayerInput>();
}

private void OnEnable() { //some code to activate the input actions }
private void OnDisable() { //some code to deactivate the input actions }

PlayerController.cs script that is attached to the player GameObject in the scene.

Be sure to add "using UnityEngine.InputSystem;" The parameter "InputAction.CallbackContext ctx" makes this device specific. If you don't include it, it will read all the input from all devices for one character. "ctx" can be called anything but "InputAction.CallbackContext" has to remain the same.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    private Vector2 movementInput;
    [SerializeField] private float MOVESPEED = 4.0f;
    private Rigidbody2D rb;


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

    public void OnMove(InputAction.CallbackContext ctx)
    {
        movementInput = ctx.ReadValue<Vector2>();
    }

    private void FixedUpdate()
    {
        //Moving the character
        rb.velocity = movementInput * MOVESPEED;
    }

}

Alternate way to move character.

//Alternate 1
rb.velocity = movementInput * (MOVESPEED * Time.fixedDeltaTime);

//Alternate 2
rb.MovePosition(rb.position + movementInput * (MOVESPEED * Time.fixedDeltaTime));

Last updated