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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

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:
    37,196
    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.