Home > other >  Unity make Joystick always result in speed 1
Unity make Joystick always result in speed 1

Time:02-23

So I have a joystick object, which gives me values of -1 to 1 for each axis.

float horizontalMove = joystick.Horizontal * speed;
float verticalMove = joystick.Vertical * speed;

rb.velocity = new Vector3(horizontalMove, verticalMove, 0);

Now, what I want is that no matter how far you pull the joystick in each direction, it will always result in speed 1. Just like how my current code works, but my joystick is always pulled to the edge. I also made it so max. 1 directions can be set to 0.

CodePudding user response:

You can use the .normalized property of the vector, which ensures it either has length 1, or is equal to Vector3.zero.

rb.velocity = new Vector3(horizontalMove, verticalMove, 0).normalized;

Unlike using Mathf.Sign on each axis, the angle of the vector is preserved, so the player will still be able to move in any orientation, not just along axes and diagonals.

  • Related