I am trying to jump with rigidbody, and sometimes my jump is low like it stacks in something and sometimes is high. Why does it change?
thank's for the answers
My code:
private void Update() {
if (Input.GetKeyDown(KeyCode.Space) && isGrounded) Jump();
}
private void FixedUpdate()
{
isGrounded = Physics.CheckSphere(groundCheck.position, 0.2f, groundMask);
}
private void Jump()
{
rigidbody.AddForce(Vector3.up * 20, ForceMode.VelocityChange);
isGrounded = false;
}
First of all, any Physics calculations regarding Rigidbody (such as the one in your Jump()) should always be done inside the FixedUpdate() function according to the Unity documentation here. FixedUpdate() runs at a default fixed rate every 0.02 seconds, whereas Update() runs once per frame, which would be different for every machine it runs on.
Instead of me reinventing the wheel for you, I done a search and found the following code on the Unity forums, here, which should help you understand your problem further. I used the code there and edited it for your scenario.
private bool shouldJump = false;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
shouldJump = true;
}
}
void FixedUpdate()
{
// Check for jump
if (isGrounded && shouldJump)
{
shouldJump = false;
rigidbody.AddForce(Vector3.up * 20.0f, ForceMode.VelocityChange);
}
}