c# – Lerping the Main Camera in Unity3D?

I have a first person camera that I’m using along with a script and when I do certain movements like crouching, I use Lerp to add a transition speed on my player position + scale so that my player crouches/stands over a very short amount of time rather than instantly. I’ve never had an issue with using Lerp but when it comes to doing the same thing with my camera, nothing happens.

public Vector3 offset = new Vector3(0f, 0.779f, 0f); // Start offset
public Vector3 newOffset = new Vector3(0f, -0.100f, 0f); // New camera position when crouching
public Vector3 originalOffset = new Vector3(0f, 0.779f, 0f); // Revert back to start offset
float lerpDuration = 1f;

public void Update()
    {
        if (Input.GetKey(KeyCode.LeftControl) && !isCrouching)
        {
            StartCoroutine(LerpCrouch());
            isCrouching = true;
        }
        else
        {
            offset = originalOffset;
            isCrouching = false;
        }
    }

IEnumerator LerpCrouch()
    {
        float timeElapsed = 0;
        while (timeElapsed < lerpDuration)
        {
            isCrouching = true;
            offset = Vector3.Lerp(offset, newOffset, timeElapsed / lerpDuration);
            timeElapsed += Time.deltaTime;
            yield return null;
        }
        offset = newOffset;
    }

The issue with the code above is, when I initially crouch, my camera instantly changes position. When I let go of the crouch key, the camera instantly reverts to its default position and then begins to Lerp from default position to crouch, which I don’t understand.

I have changed GetKey to GetKeyDown and also the code inside the else statement but the results are the same.

Read more here: Source link