Search Unity

Does anyone know how to get 8-directional movement with a joystick?

Discussion in 'Scripting' started by JFGames, Oct 26, 2019.

  1. JFGames

    JFGames

    Joined:
    Jan 15, 2017
    Posts:
    3
    I've been at it for weeks now and nothing I try is working. I get 8-directional movement on keyboard just fine (which makes since as there's only eight possible inputs on a keyboard) but anytime I plug in a controller I get some very nice 360 movement. This would be great if I didn't need to limit the player to eight directions for my game to function correctly. Any ideas?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    You just need to quantize each axis independently before using the result.

    Each axis returns from -1.0f to 0.0f to 1.0f.

    The simplest way to quantize it is something like this:

    Code (csharp):
    1. int QuantizeAxis ( float input)
    2. {
    3.   if (input < -0.5f) return -1;
    4.   if (input > 0.5f) return 1;
    5.   return 0;
    6. }
    You can tinker with the 0.5, which is the deadband within -1 to 1 where you want zero to come out.

    You can also put each axis into a Vector2 and then normalize the result so that diagonals don't go 1.41x (square root of 2) faster than horizontal/vertical movement.
     
  3. JFGames

    JFGames

    Joined:
    Jan 15, 2017
    Posts:
    3
    Thanks! That was the exact solution I was looking for.
     
    Kurt-Dekker likes this.