How can I smooth out the crouch movement?

I know this question has been asked before, but I didn’t understand any of the answers.
My crouch script works, but it is not smooth. The camera just teleports instead of smoothly moving down. Here’s my code: (by the way: I cut out the part where I resize the collider and the center of the character controller and so on… for the sake of clearness)

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

	private bool crouch = false;
	
	private CharacterMotor charMotor;
	private CharacterController charCont;
	
	void Start (){
	
		charMotor = GetComponent<CharacterMotor>();
		charCont = GetComponent<CharacterController>();
	}
	// Update is called once per frame
	void Update () 
	{
			if(Input.GetButtonDown("Crouch"))
			{
				crouch=true;
			
				Camera.main.transform.localPosition = new Vector3(0, -crouchHeightOffset, 0); 
				charMotor.movement.maxForwardSpeed -= 3.4f;
				charMotor.movement.maxBackwardsSpeed -= 3.4f;
				charMotor.movement.maxSidewaysSpeed -= 3.4f; 
			}

			if (Input.GetButtonUp("Crouch"))
			{
				crouch=false;
			
				Camera.main.transform.localPosition = new Vector3(0,0,0);
				charMotor.movement.maxForwardSpeed += 3.4f;
				charMotor.movement.maxBackwardsSpeed += 3.4f;
				charMotor.movement.maxSidewaysSpeed += 3.4f; 
			}

		if (crouch)
			charMotor.jumping.enabled=false; else charMotor.jumping.enabled=true;
		
	} 
	
	
}

I tried Mathf.Lerp, Mathf.SmoothDamp, Mathf herpderp, Vector3.Lerp, almost everyting I guess… I just can’t get it to work. How does this Lerp and SmoothDamp work EXACTLY? (Sorry, but I really don’t understand S*** of those docs about Lerp and SmoothDamp).

I hope somebody can help me out with this :slight_smile:

You need to call SmoothDamp() repeatedly until you’re within the desired threshold of your goal value.

Try something like this (untested code):

private float smoothTime = 0.3f; // Smoothly crouch/uncrouch over 0.3 sec.
private float targetY = 0; // Where we want camera local Y to be.
private float velocityY = 0; // Velocity toward targetY.

void Update() {
    if (Input.GetButtonDown("Crouch")) {
        crouch=true;
        targetY = -crouchHeightOffset;
        charMotor.movement.maxForwardSpeed -= 3.4f;
        charMotor.movement.maxBackwardsSpeed -= 3.4f;
        charMotor.movement.maxSidewaysSpeed -= 3.4f;
    }
 
    if (Input.GetButtonUp("Crouch")) {
        crouch=false;
        targetY = 0;
        charMotor.movement.maxForwardSpeed += 3.4f;
        charMotor.movement.maxBackwardsSpeed += 3.4f;
        charMotor.movement.maxSidewaysSpeed += 3.4f;
    }

    // Smoothly update the camera position one step closer to where we want it.
    float newY = Mathf.SmoothDamp(Camera.main.transform.localPosition.y, targetY, ref velocityY, smoothTime);
    Camera.main.transform.localPosition = new Vector3(0, newY, 0);

    charMotor.jumping.enabled = !crouch;
}