- Home /
slow down crouch
when i crouch, its almost like i am teleporting to a lower level. any ideas on how to slow it down? (i am new to unity)
public class crouch : MonoBehaviour
{
public CharacterController CT;
public float activeCrouch = 1f;
public float notCrouch = 3f;
public GameObject player;
// Start is called before the first frame update
void Start()
{
CT = gameObject.GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
CT.height = activeCrouch;
player.transform.localScale = new Vector3(1f, 1f, 1f);
}
else
{
CT.height = notCrouch;
player.transform.localScale = new Vector3(1f, 2f, 1f);
}
}
}
Comment
Answer by jkpenner · Apr 21, 2020 at 03:34 AM
I would suggest using a Lerp to interpolate between your default height and crouch height. Something similar to this:
// Determine if which height we need to move towards.
var crouchDirection = isCrouched ? -1 : 1;
// crouchValue is clampped between 0 to 1 The value will be adjusted by the
// current crouch direction.
crouchValue = Mathf.Clamp01(crouchValue + (crouchDirection * Time.deltaTime));
// lerp between the crouchHeight and default height based on the crouchValue.
// When crouchValue is 0 it returns the crouch height, when it is 1 it returns
// the default standing height, and any value inbetween will return a value
// between the default and crouch heights (0.5 returns half way between).
var targetHeight = Mathf.Lerp(crouchHeight, defaultHeight, crouchValue);