Search code examples
c#unity-game-enginesmoothinglerpclamp

How do I smoothly clamp controller input?


I'm trying to rotate an object according to the stick input on a controller, and then clamp it at a maximum rotation. When I use Mathf.Clamp() the rotation just hits that wall, and it doesn't feel good. I've tried using Mathf.SmoothDamp() as well and that creates similar results. Is there a way to smoothly approach the max rotation angle while taking the stick input into account?

    void Update()
    {
        SmoothRotate();
    }

    void SmoothRotate()
    {
        rotateX += iR.leftStickY * rotationSensitivity * Time.deltaTime;
        rotateX = Mathf.Clamp(rotateX, -maxPitchAngle, maxPitchAngle);
        currentRotX = Mathf.Lerp(currentRotX, rotateX, .5f);

        rotateZ += iR.leftStickX * rotationSensitivity * Time.deltaTime;
        rotateZ = Mathf.Clamp(rotateZ, -maxPitchAngle, maxPitchAngle);
        currentRotZ = Mathf.Lerp(currentRotZ, rotateZ, .5f);

        transform.eulerAngles = new Vector3(currentRotX, currentAngle.y, currentRotZ);
    }

Any help is greatly appreciated.


Solution

  • Try this Stuff

     public float mouseSensitivity = 10.0f;
     public Transform target;
     public float dstFromTarget = 2.0f;
     public float yaw;
     public float pitch;
     public Vector2 pitchMinMax = new Vector2(-50, 85);
     public float rotationSmoothTime = 0.02f;
     Vector3 rotationSmoothVelocity;
     Vector3 currentRotation;
    
    
     void Update()
     {
         SmoothRotate();
     }
    
     void SmoothRotate()
     {
         //Mouse Movement
         yaw += iR.leftStickX * mouseSensitivity;
         pitch -=  iR.leftStickY * mouseSensitivity;
     
         // Clamp
         pitch = Mathf.Clamp(pitch, -maxPitchAngle, maxPitchAngle);
    
      
         transform.eulerAngles = Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime);
       
    
     }