cookertron
cookertron

Reputation: 198

Jumping, a python solution

I'm trying to work out how to make a character jump a specified height and within a specified number of steps and be effected by a gravitational force. For instance, jump 400px within 50 steps.

So far I can simulate a rocket effect so that starting velocity is slow but by the time 50 steps is up it will have reached a height of 400px like this:

HEIGHT = 400
STEPS = 50

g = 2.0 * HEIGHT / (STEPS * (STEPS - 1))

y = 0
velocity = 0

for index in range(STEPS):
    y += velocity
    velocity += g

print y, velocity # prints 400.0 16.3265306122

I've tried starting the velocity at -16.3265306122 and adding g each step but that doesn't result in y = -400, velocity = 0 as you'd except. The result of doing it like that is y = -416.32653061 and velocity = 4.49112969036e-11.

What do you think?

Upvotes: 0

Views: 126

Answers (2)

Sach
Sach

Reputation: 912

when you are increasing the y (height) you are staring from velocity as zero, so in first step value of y is zero.

When you are starting at y=0 and velocity as -16.3265306122, in first step you are travelling 16.32653061, which is the difference.

Instead of negative velocity, try with negative value of g. (while coming down you should feel negative of what you felt going up.)

Upvotes: 1

Mike O'Connor
Mike O'Connor

Reputation: 2710

In the first run you're estimating the integral of velocity over time using the lowest value that velocity actually has during each step. Then the last value of the velocity that you get from velocity += g is printed out but was never used in the integration. So in going the other way you could start with a velocity of -16, which is the value before the last, the last one that was actually used. That will get you -400 0.326530612245 and the second number, the new last velocity, is again not used in the integration and is the value of g. So you could simply revise the code to not print out the unused last velocity:

for index in range(STEPS):
    y += velocity
    used_velocity = velocity
    velocity += g
print y, used_velocity

Upvotes: 1

Related Questions