# How to jump always with the same height

Hello guys, i have a problem. I’m using physics 2D, and i’m trying to make a character jump always the same height with Addforce, but in vain.

``````acceleration = (rigidbody2D.velocity - lastVelocity) / Time.fixedDeltaTime;
lastVelocity = rigidbody2D.velocity;
force = rigidbody2D.mass * Mathf.Abs(acceleration.y);
``````

and have already tryed make velocity zero when clicked before addforce but nothing:

``````rigidbody2D.velocity = new Vector2(0,0);
``````

Can sound easy but is tricky. Any ideas?

You can set rigidbody2D.velocity’s y component to some value that’ll reach the height you want. You just need to calculate what that y value needs to be in order to counter-act gravity for long enough that the apex of the jump occurs at the height you want.

Luckily, Unity’s CharacterController package comes with an example of how to do this in Javascript, which I’ve appropriated to 2D for you:

``````function CalculateJumpVerticalSpeed (targetJumpHeight : float)
{
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2 * targetJumpHeight * Physics2D.gravity.y);
}
``````

And in C#, it’d be:

``````public static float CalculateJumpVerticalSpeed(float targetJumpHeight)
{
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2f * targetJumpHeight * Physics2D.gravity.y);
}
``````

Then, to set the velocity of your Rigidbody2D, you’d use this in Javascript:

``````var velocity : Vector2 = rigidbody2D.velocity;
velocity.y = CalculateJumpVerticalSpeed(myJumpHeight);
rigidbody2D.velocity = velocity;
``````

or in C#, it’d be:

``````Vector2 velocity = rigidbody2D.velocity;
velocity.y = CalculateJumpVerticalSpeed(myJumpHeight);
rigidbody2D.velocity = velocity;
``````