How to round joystick input to 1 or -1?

510 Views Asked by At

GOAL
So I want my game to support xbox / playstation controllers. I want the joystick to allow you to move left / right, at one speed, no matter how far the joystick is moved.

PROBLEM
However when I test the game with a controller, pushing the joystick only a little bit will make the character move slower.

CODE

void Update() {
   //Takes input for running and returns a value from 1 (right) to -1 (left)
   xInput = Input.GetAxisRaw("Horizontal");

   Jump();  
}

Of course this 'bug' is caused because the controller has the ability to return a float value between -1 and 1.
However I want to know how to round this value to -1 or 1, or somehow disable the controller's ability to return a float value, because something like

xInput = Input.GetAxisRaw("Horizontal") > 0 ? 1 : -1;

Means that [no input] would return as -1, and

if (Input.GetAxisRaw("Horizontal") > 0) {
   xInput = 1;
} else if (Input.GetAxisRaw("Horizontal") < 0) {
   xInput = -1;
}

Just seems unecessary and not elegant

1

There are 1 best solutions below

1
On BEST ANSWER

If I understand you correct, you are looking for Math.Sign:

  • -1 if argument is negative
  • 0 if argument is zero
  • 1 if argument is positive

Code:

xInput = Math.Sign(Input.GetAxisRaw("Horizontal"));

Edit:

If we want some kind of dead zone (i.e. xInput == 0 if magnitude is less the some tolerance), see Chuck Walbourn's comments:

float tolerance = ...;

xInput = Input.GetAxisRaw("Horizontal");

xInput = Math.Abs(xInput) < tolerance
  ? 0.0
  : Math.Sign(xInput);