Gravity turns an unrealistic game into something much more pleasing to the eye. The brain is very good at spotting movement that doesn’t seem real and gravity is one area where this is apparent.
PICO-8 has no in built physics functions and anyway, where’s the fun in that!
The key to gravity is that we move away from directly controlling the x and y location of the object directly to controlling its velocity. To model this the first principle to remember is that the velocity of an object in the x and y directions (vx and vy) are unrelated to each other. When dealing with gravity we are only interested in movement along the y axis.
To model gravity we must understand that gravity is an acceleration. That is it constantly increases the speed of an object towards ground (I’m dealing with simple platform style gravity here, to model orbital gravity see my post here).
So, first of all we need a value (g) which models the acceleration due to gravity. This will be applied every update cycle, so it could do with being small. It is set in _init().
g=0.1
Then, every update cycle you need to increase the speed of the object by g. Remember that in PICO-8, as with most languages, positive is down.
vy+=g
Finally we change the y location by the velocity
y+=vy
That’s all there is to it!
Obviously there is a lot more to adding this to a game. Collisions need modelling and adding a jump to a character is usually required. Collisions are another topic all together, but to jump just set the y velocity to a negative value.
vy=-2
I’ve included a simple cart with a bouncing ball to show how this can be put together.
Happy programming!
Gravity cart:
Thanks, Doc Robs. This simple bit of code helped me with my first Pico8 game I’m working on.