#how to calculate the force necessary to reach an exact height
1 messages · Page 1 of 1 (latest)
#💻┃code-beginner message my contribution
float CalculateInitialVelocity(float jumpHeight, float fixedTimestep, float acceleration) {
// start at 0 speed - this is at the top of the jump
float speed = 0;
// work backwards to get to starting speed
for (float height = jumpHeight; height > 0; height -= speed * fixedTimestep) {
speed += acceleration * fixedTimestep
}
return speed;
}
can you explain to me what it does
it works backwards
imagine yourself at 0 velocity at the top of the jump (the desired height)
it then simulates each fixed physics timestep, adding velocity as gravity would, until the object reaches the ground
the final velocity is the same as you would need to get to that height in the first place
basically it's the same as if you drop an object off a height, then record its velocity as it hits the ground
that's the same velocity you'd need to throw the object to that height from the ground
if im at the desired height speed is 0, and then it calculates every physics frame until i get to 0?
yes
I'm not sure if there's a way to do it all at once (without a loop) but this should at least work as a starting point
i then do rb.addforce(CalculateInitialVelocity)
well this will just give you a float
so you'd use that as the y velocity you are assigning your player
something like cs rb.velocity = new(rb.velocity.x, CalculateInitialVelocity(desiredJumpHeight, Time.fixedDeltaTime, gravity), rb.velocity.z);
and then just jump in fixedupdate?
jump wherever you want to jump 🤷♂️
basically
FixedUpdate()
{
if (should be jumping)
rb.velocity...
}