I wrote a co-routine that zooms in on the character when idle (no keys pressed) and zooms out to the original size when a the character starts moving (any key is pressed). When zooming in the lerp function I wrote works as expected, it zooms smoothly towards the character. However when It zooms out it doesn’t lerp but zooms out instantly and I can’t warp my mind around why it behaves like that.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraZoom : MonoBehaviour
{
[Header("Configuration Parameters")]
[SerializeField] private int zoomFactor;
[SerializeField] private float zoomSpeed;
[Header("Componenets")]
[SerializeField] private PlayerController player;
[Header("Variables")]
private float originalSize;
private float counter;
private IEnumerator Zoom()
{
counter = 0f;
while (true)
{
if (Input.anyKey == false)
{
counter += zoomSpeed;
Camera.main.orthographicSize = Mathf.Lerp(originalSize, zoomFactor, counter);
yield return null;
}
else
break;
}
counter = 0f;
while(true)
{
if (Input.anyKey == true)
{
counter += zoomSpeed;
Camera.main.orthographicSize = Mathf.Lerp(zoomFactor, originalSize, counter);
yield return null;
}
else
break;
}
}
void Start()
{
originalSize = Camera.main.orthographicSize;
}
void Update()
{
StartCoroutine(Zoom());
}
}