Search Unity

[Solved] Smooth 2D joystick rotation

Discussion in 'Scripting' started by QuinnWinters, Aug 1, 2020.

  1. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    494
    I'm attempting to make an xbox controller smoothly rotate a 2D object on its z axis. I have achieved rotation in a multitude of ways, but it's never smooth. It visibly jumps from 0 to 45 to 90 and so forth. This is running from FixedUpdate. Here are two different attempt examples. What am I doing wrong?

    Code (CSharp):
    1. float horizontal = Input.GetAxis ("Horizontal Joystick 2") * Time.deltaTime * 1;
    2. float vertical = Input.GetAxis ("Vertical Joystick 2") * Time.deltaTime * 1;
    3. float angle = Mathf.Atan2 (horizontal, vertical) * Mathf.Rad2Deg;
    4. thisTransform.rotation = Quaternion.Euler (new Vector3 (0, 0, angle));
    Code (CSharp):
    1. float currentAngle = thisTransform.eulerAngles.z;
    2. float newAngle = Mathf.Atan2 (CrossPlatformInputManager.GetAxis ("Vertical Joystick 2"), CrossPlatformInputManager.GetAxis ("Horizontal Joystick 2")) * 180 / Mathf.PI;
    3. float angle = Mathf.LerpAngle (currentAngle, newAngle, Time.time);
    4. thisTransform.eulerAngles = new Vector3 (0, 0, angle);
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    The problem is not in the code above. Most likely you have something set in the input manager to quantize each axis' input to -1, 0 or 1.

    To test this, print out the raw float values you get back from the Input system. If they do not traverse smoothly from -1 through 0 to 1, that's the problem, go check settings on whatever input system you're using.

    Debug.Log() should always be the first thing you reach for: start printing out data so you know.
     
  3. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    494
    Thanks for the response. It turned out the issue was that I was using Time.time in the second example instead of Time.deltaTime. Time.deltaTime * 6 gave the joystick a nice smooth rotation.
     
    Kurt-Dekker likes this.