How to configure Unity Input Actions map for four direction movement?

Viewed 287

I have a Unity game where you can only move to one of four directions. So the direction should be of type Vector2Int where

  • one axis must be 0
  • the other axis must be -1 or 1

Let me show you my current input configuration

enter image description here

and for the KeyboardWASD input

enter image description here

Do I have to code this on my own like

public sealed class MovementDirectionInputBehaviour : MonoBehaviour
{
    public void ReplaceMovementDirectionInput(InputAction.CallbackContext context)
    {
        Vector2 input = context.ReadValue<Vector2>();
        
        // if one axis is 0

        // and the other one is -1 or 1

        // then do stuff

        // else ... ignore it? horizontal beats vertical?
    }
}

or is there a way to configure the input map to do exactly that?


Edit

I added a new press interaction

enter image description here

but when trying to read the value

Vector2Int newInput = inputContext.ReadValue<Vector2Int>();

I get the following errors

enter image description here

Do I have to stick to Vector2 and can be sure the values will always be integer or do I have to configure each key with a processor?

Any better solutions than this one?

public void ReplaceMovementDirectionInput(InputAction.CallbackContext inputContext)
{
    Vector2 newInput = inputContext.ReadValue<Vector2>();

    Vector2Int fixedInput = new Vector2Int(
        Mathf.RoundToInt(newInput.x), 
        Mathf.RoundToInt(newInput.y));
}
1 Answers

enter image description here

void Start()
{
    if (InputAction != null)
    {

        InputAction.FindAction("Movement").performed += ReplaceMovementDirectionInput;
        InputAction.FindAction("Movement").canceled += ReleaseMovementDirectionInput;
        InputAction.Enable();
    }
}

/// <summary>
/// Cache current direction status.
/// </summary>
Vector2 m_currentDirection = Vector2.zero;
public Vector2 CurrentDirection
{
    get { return m_currentDirection; }
    set
    {
        // If the state changes. 
        if (m_currentDirection != value)
        {
            m_currentDirection = value;

            //The input(cache) is already a direction variable, Just change the direction of the character.
            //e.g:
            //    transform.Translate(new Vector3(cache.x, cache.y, 0) * Time.deltaTime * speed);
            // or transform.Translate(new Vector3(cache.x, 0, cache.y) * Time.deltaTime * speed);
            // TODO : Control  the character movement;
        }
    }
}

private void ReleaseMovementDirectionInput(InputAction.CallbackContext obj)
{
    CurrentDirection = Vector2.zero;
}

private void ReplaceMovementDirectionInput(InputAction.CallbackContext ctx)
{
    CurrentDirection = ctx.ReadValue<Vector2>();
}

Related