- Home /
smooth fps movements using joystick
I am trying to have a FPS moving inside a 3D environment using a joystick. However, with the current code that I have the movements are like steps. I want to change it so that when the user presses a button on the joystick, the player will move smoothly and continuously while the button is being pressed.
Here is what I have:
void Update()
{
if (Input.GetKeyDown(KeyCode.Joystick1Button0))
cam1.transform.Translate(0, 0, -5f);
if (Input.GetKeyDown(KeyCode.Joystick1Button1))
cam1.transform.Rotate(0, 5f, 0);
if (Input.GetKeyDown(KeyCode.Joystick1Button2))
cam1.transform.Rotate(0, -5f, 0);
if (Input.GetKeyDown(KeyCode.Joystick1Button3))
cam1.transform.Translate(0, 0, 5f);
}
I tried using Quaternion.Lerp for rotations to the right and left, but i don't know how to exactly set the first two input parameters to the Lerp function (the from and to).
Thank you for any help :)
Answer by iJuan · May 14, 2018 at 04:30 PM
Use Input.GetAxis("Horizontal")
for horizontal movement, and Input.GetAxis("Vertical")
for vertical movement. Both methods return a float which indicates the "strength" of the movement. It's values ranges from -1 to 1
Also, you can rotate the rigidbody instead of the transform itself to make it look smoother (and keep moving a little after the stick being released, how strong it's rotation desaccelerates depends on "Angular Drag".
Thank you iJuan
I tried it the way you said. It works nice and smoothly with keyboard buttons. However i have a problem with joystick. As soon as I press a button on joystick, the character starts moving and even when I let go of the button the movement does not stop! I think my settings in the input manager are fine, but cannot find a way to stop the character after releasing the stick.
Any ideas how to resolve it?
Add "Debug.Log(Input.GetAxis("Horizontal"));" At the end of your code.
Share the resulting code, and that debug's output after releasing the stick.