I’m trying to add a smooth transitioning from my initial player’s height to crouching, but it’s just snapping. I followed this tutorial: How to Use Lerp (Unity Tutorial) - YouTube. Thanks in advance
Here’s my crouch method:
void Crouch()
{
elapsedTime += Time.deltaTime;
float percentageComplete = elapsedTime / desiredDuration;
if (Input.GetKeyDown(KeyCode.LeftAlt))
{
transform.localScale = Vector3.Lerp(playerHeight, crouchHeight, percentageComplete);
}
if (Input.GetKeyUp(KeyCode.LeftAlt))
{
transform.localScale = Vector3.Lerp(crouchHeight, playerHeight, percentageComplete);
}
}
Hello! I would recommend giving us the full script. However, there are a few things I could see happening. First off, make sure that desiredDuration is a variable of type float and not int. Secondly, I would try making your Input.GetKeyDown to Input.GetKeyAnd clamp percentageComplete to 1 so do percentageComplete = Mathf.Clamp(percentageComplete, 0, 1). And for your unshifting, that will never smoothly do it. What you will have to do is have a coroutine.
Your coroutine would look like this.
IEnumerator OnUncrouch() {
float t = 0;
float frac = 0;
while (frac < 1) {
t += Time.deltaTime;
frac = t / desiredDuration;
transform.localScale = Vector3.Lerp(crouchHeight, playerHeight, frac);
yield return null;
}
}
And then in side of your Input.GetKeyUp(KeyCode.LeftAlt) put in
IEnumerator coroutineVal = OnUncrouch();
StartCoroutine(coroutineVal);
Hope this helps!
(I have never gotten a upvote, would be much appreciated.)