Hello,
this is my Player script and i added a Crouch function. If i press C it crouch down but if i press C again it will not stand up! What did i wrong?
public int playerID = 0;
[Header(“General”)]
public CharacterController cc;
public bool canControl = true;
public GameObject cam;
[Header("Movement")]
public float walkSpeed;
public float runSpeed;
public float crouchSpeed;
public float gravity;
public float jumpForce;
public float crouchHeight;
//private vars
private int movementState = 0; // 0 standing , 1 walking , 2 running , 3 crouching , 4 vehicle , 5 ladder , 6 injured , 7 air
private Vector3 movement = Vector3.zero;
private bool canRun;
private bool canJump;
private float height;
void Start()
{
height = cc.height;
}
void Update()
{
if (cc.isGrounded && canControl)
{
movement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
movement = transform.TransformDirection(movement);
movement *= walkSpeed;
if (Input.GetButtonDown("Jump"))
{
movement.y = jumpForce;
}
if (Input.GetButton("Sprint"))
{
movement *= runSpeed;
}
if (Input.GetButtonDown("Crouch"))
{
Crouch(crouchHeight,crouchSpeed);
}
}
else
{
movementState = 7;
}
movement.y -= gravity * Time.deltaTime;
cc.Move(movement * Time.deltaTime);
}
void Crouch(float height, float crouchSpeed)
{
if(movementState != 3) // if we are not crouching
{
cc.height = Mathf.Lerp(height, crouchHeight, 3f);
movementState = 3;
}
else //if we are crouching stand up
{
cc.height = Mathf.Lerp(cc.height, height, 3f);
movementState = 0;
}
}
Thanks in advance and Best Regards,
T