Calculate Gravity/jump In Pygame
Solution 1:
Super Mario clones typically move a specific amount of time up, then down until he hits something solid (the floor, or possibly a turtle). As you may know, it looks very unrealistic.
The physics formula for "jumping and falling" is: d = (at²)/2
, where d
is the distance jumped up, a
is the gravity, and t
is the time. However, for a simple game that can be adjusted :)
- Set a target 'height' for your jumps; for example, 32 pixels in total.
- Use
1
for gravity. - Measure time
t
in game ticks. That gives you the time it takes to reach 32 pixels:
32 = (t²)/2 t² = 64 t = 8
The 'speed' of your jump is
v = at
. Since you assumea=1
above,v = t
, i.e.,v = 8
. As it appears, your initialypos
needs to be set tospeed/2
(probably because this is an approximation..)- In each next game tick, add
speed
to your y position and subtract 1 fromspeed
Now the following will happen in each game tick from the moment you press 'up' (assuming
y=0
at start):speed = 8
->y=4
(since this is "jump 0")speed = 7
->y=11
speed = 6
->y=17
speed = 5
->y=22
speed = 4
->y=26
speed = 3
->y=29
speed = 2
->y=31
speed = 1
->y=32
speed = 0
->y=32
speed = -1
->y=31
speed = -2
->y=29
... down to 0 again (but check on overflow for lower-than-zero).
On the "half speed" fix: strange .. the math works out this way (you hover for just a moment on exactly the right height) but I can't figure out off-hand why you should not start with the actual speed.
Edit
Just thought of the reason why my maths seemed off.
The problem lies in my statement that if your initial velocity -- at Start of Jump -- is 8
(pixels per game tick), you end up exactly 8 pixels higher at the "end" of that tick. You don't, because the "gravity" kicks in immediately, as soon as you leave the ground. At the "end" of the game tick, your speed has decreased to 7
; therefore, your average speed is not 8
from start to end of this tick, it's only 7.5
, and you end up on an y-pos of 7.5 pixels. The same goes for every next tick; your speed still decreases with 1
per tick.
So, after the (correctly calculated!) total jumping-up time of 8 ticks, you traveled
7.5 + 6.5 + 5.5 + 4.5 + 3.5 + 2.5 + 1.5 + 0.5 = 32 pixels
It's possible to "correctly" implement it, but it introduces floating-point arithmetics in what is currently an integer-only calculation, and it would require you to draw your sprite at an y position of "7.5 pixels". Floating-point calculations may suffer from rounding and 'exact' comparison issues, so that's why it is best to avoid it where possible -- certainly for this kind of simple physics.
Post a Comment for "Calculate Gravity/jump In Pygame"