1

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

LWB
  • 426
  • 1
  • 4
  • 16
  • Isn't that the cool thing about a joystick though? Otherwise why use a joystick and not simply the keyboard? – derHugo Jan 09 '22 at 21:52
  • @derHugo The game im making uses directional input, which is hard to control on mouse and keyboard, and my character will have acceleration when they do small adjustments, the character will move slow. Also animations for running wouldnt look right when going slow :/ – LWB Jan 09 '22 at 22:39

1 Answers1

2

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);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • For gamepads and joysticks, you need to handle the 'dead-zone' as well since these devices are often 'noisy'. You may find this blog post useful to reference: https://shawnhargreaves.com/blog/gamepads-suck.html and my implementation https://github.com/microsoft/DirectXTK/blob/main/Src/GamePad.cpp – Chuck Walbourn Jan 10 '22 at 21:35