- Home /
How do I create joystick controls with two fixed speeds? (3D)
I'm trying to make joystick controls that have two fixed speeds, walk and run, with no sensitivity. The problem I'm encountering is that without directly using the axis input, the player's rotation becomes stiff as though using WASD, which is exactly what I don't want. My current workaround is to determine which input is greater and set it to a fixed speed while the other is input sensitive. This creates the illusion of fixed speed, but it still doesn't do what I want. (The stiff movement still occurs when walking.) Here's the code I have right now:
totInput = Mathf.Sqrt(hInput * hInput + fInput * fInput);
// Determine Speed
if (totInput > 0.7f)
speed = speedFast;
else
speed = speedSlow;
// Horizontal Movement
if (hInput != 0)
{
if (Mathf.Abs(fInput) >= Mathf.Abs(hInput))
transform.Translate(Vector3.right * speed * hInput * Time.deltaTime);
else
transform.Translate(Vector3.right * speed * hSign * Time.deltaTime);
}
// Forward Movement
if (fInput != 0)
{
if (Mathf.Abs(fInput) <= Mathf.Abs(hInput))
transform.Translate(Vector3.forward * speed * fInput * Time.deltaTime);
else
transform.Translate(Vector3.forward * speed * fSign * Time.deltaTime);
}
(As a note, I'm currently using a rigidbody but I want to switch to using a character controller. Also, sorry if my code is a little wack. I'm new to Unity and I'm transitioning from java to C#.)
Answer by Master109 · Feb 23 at 01:59 AM
Maybe I am misunderstanding the question but to avoid stiff rotation like WASD set the player's rotation using:
transform.rotation = Quaternion.LookRotation(new Vector3(hInput, 0, fInput), Vector3.up);
I attempted to use this in my code, but I couldn't figure out how to use it to solve my problem. For reference, this is what I tested in a sandbox script: move = new Vector3(hInput, 0, fInput); if (move != Vector3.zero) transform.rotation = Quaternion.LookRotation(move, Vector3.up); controller.SimpleMove(move * speed);
Still, the translation is determined by the input sensitivity (i.e. slightly tilting the joystick results in a crawling speed, whereas I want it to always be the walking speed). Is there another way to approach this using rotation instead of translating the xyz positions?
Ah, I get the problem now. Add ".normalized" after move to make the length of the vector equal to 1: controller.SimpleMove(move.normalized * speed);