Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to round joystick input to 1 or -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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading