Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Cannot figure out how to enable 4 way movement in new InputSystem

Discussion in 'Input System' started by dzizzy, Sep 6, 2020.

  1. dzizzy

    dzizzy

    Joined:
    May 7, 2019
    Posts:
    2
    Hey everyone,

    I can't figure out how to disable diagonal movement with the new InputSystem, and I can't find any results on Google either. I'm trying to create 4 directional movement like in old RPGs, e.g. Pokemon in the Gameboy days

    How would I go about tackling this?
     
  2. dzizzy

    dzizzy

    Joined:
    May 7, 2019
    Posts:
    2
    Well if anyone ever has the same question and comes across this, I have a convoluted solution by taking the XOR of the absolute value of the normalized movement vector's x and y.
    Basically, normalizing the vector restricts the values between -1 and 1, and casting the absolute value of x and y to int ensures they're either 0 or 1. Then A XOR B only equals 1 if both A and B differ. We also allow no movement to stop.

    Code (CSharp):
    1.  
    2. public void OnMove(InputAction.CallbackContext context)
    3. {
    4.     Vector2 move = context.ReadValue<Vector2>().normalized;
    5.     if (((int)Mathf.Abs(move.x) ^ (int)Mathf.Abs(move.y)) == 1
    6.            || move.Equals(Vector2.zero))
    7.     {
    8.         rigidBody.velocity = speed * move;
    9.     }
    10. }
     
    Last edited: Sep 6, 2020
    SpiderPig1660 likes this.