Understanding the physics

Hi,

This questions isn’t really to solve a problem but to understand a solution I’m using. I have a character in an environment (with a ground) and implemented a jump. The solution I came up with is that when the button is pressed I add a force in the y direction.

rigidbody.velocity = new Vector3(rigidbody.velocity.x, 0, rigidbody.velocity.z);
rigidbody.AddForce(new Vector3(0, jumpAmount, 0), ForceMode.Force);

If I remove the first line the amount that the character jumps is very random when starting at rest, (i.e. on the ground) sometimes he jumps 2 inches and sometimes he’ll jump 20 feet. I’m curious as to why that is the case. Shouldn’t the force act more predictable (I understand there are always going to be minor differences) whether I zero the velocity out first or not? So my questions is essentially does anyone know why it would behave so randomly without the first line?

Thanks in advance

According to the Unity documentation in most cases you shouldn’t modify the velocity directly, nor set the velocity on every physics step.

I’m thinking what may be happening in your first line of code is you’re trying to set the velocity continuously via your input.

Try this code in your game and see if the jumping behaviour improves…

function FixedUpdate () {
    if (Input.GetButtonDown ("Jump")) {
        rigidbody.velocity = Vector3(0,10,0);
    }
}