GRAVITY:One of the most basic Physics concepts that you might want to implement in a game is gravity. Whether it be in a platformer, a pinball game, or something else, gravity is a common need. So to start off, we need to ask ourselves, what it gravity? Gravity acts on all objects on earth, and pulls the objects towards the surface, we all know that. But its not merely as simple as decreasing the players position by 1 each frame, things don't fall that way*, as they fall they get faster and faster. This phenomenom is known as
acceleration and is the concept behind gravity and all accelerating physics.
Acceleration is measured in X Meters per second per second. That is to say, every second, your velocity will increase by X Meters per second. Since we live in the game world, it would be more somthing like X pixels per frame per frame. That is to say, every frame, your velocity will increase by X pixels per frame. Lets say your position starts at 0 and your velocity starts at -3 and you are in an empty world with 1 P/F/F
acceleration (1 pixels per frame per frame). This chart shows your position, velocity, and acceleration for a few frames
Frame Position Velocity Acceleration
0 0 -3 1
1 -3 -2 1
2 -5 -1 1
3 -6 0 1
4 -6 1 1
5 -5 2 1
6 -3 3 1
7 0 4 1
8 4 5 1
9 9 6 1
10 15 7 1
The code for this would look something like
0->X
-3->V
1->A
While 1
Output(1,1,X)
X+V->X
V+A->V
End
Notice that even when the velocity is positive, the position can still be negative, and vica versa. But you can see that the position starts off moving downwards, stops at -6, then starts moving upwards again. Acceleration stays constant througout the entire simulation. If you want to get really technical, you can go into how velocity is the derivative of position blah blah blah, but you dont need to know that in a game
HOW TO USE IT:Implementing acceleration is simple, especialy if your acceleration is constant. You only need a single variable for your position and one for your velocity. If you want changing acceleration you could add a variable for that too.
Also note that X velocity is INDEPENDANT of Y velocity. That is to say, if your character has a velocity in the X direction, and has gravity affecting it, since gravity is only in the Y direction (unless your game is uber cool) the Y acceleration will only affect the Y velocity will only affect the Y position. Try this example program for size:
ZStandard
ZInteger
AxesOff
Clrdraw
0->X
0->Z
0->A
0->B
While 1
PtOff(X,Z,2
X+A->X
Z+B->Z
PtOn(X,Z,2
getKey->K
A+(K=26)-(K=24)->A
B+(K=25)-(K=34)->B
End
Its a fun example of the power of acceleration, see if you can add gravity to it! You might have some interesting results.
WHAT TO WATCH OUT FOR:Acceleration is not always applied, for example when you are standing on a platform, both your velocity and your acceleration are 0. More on this will be covered in the next section 'Collisions'