Why is this fi statement not working??
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
Answer by Vollmondum · Jul 22, 2017 at 07:19 PM
if(movementState != 3) // if we are not crouching
{
cc.height = Mathf.Lerp(height, crouchHeight, 3f);
movementState = 3;
return; // if you don't exit the method, it changes your movementState to 3 and the next frame is executed. So basically you're standing up and crouching back again :)
}
else //if we are crouching stand up
{
cc.height = Mathf.Lerp(cc.height, height, 3f);
movementState = 0;
}
Thanks to your answer! But It is still now working :(( THe player is not standing up!!
Please i need to fix that :((
Regards, T
That's not true. Lerp is just a mathematical function that returns a value based on 3 other values and it does not matter where you call it.
The way the OP is using Lerp doesn't make much sense but it does cause a change in height if the 1st and 2 nd parameters are correct.
Because he uses a third parameter greater than 1, Lerp always returns the 2nd parameter, so he could as well replace Lerp with just assigning the second parameter and things would work the same way.
if(movementState != 3)
{
cc.height = crouchHeight;
movementState = 3;
}
else
{
cc.height = height;
movementState = 0;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612130903im_/https://answers.unity.com/themes/thub/images/avi.jpg)