Gravity

The concept of gravity is important to many different types of games. Unless your game takes place in space or in some alternate gravity-less universe, you’ll probably want your players or objects to either stay on the ground or float back to the ground when they jump in the air. There are several ways to create the illusion of gravity, and we’ll explore one of the easiest in the following example.

Start by opening the program demo13-01.bb, which includes several features that have already been covered in the book. We have a sky, created by a sphere; a terrain with a collision set up between our character (a sphere with a pattern) so that he doesn’t fall through the terrain; and controls set up to move around. Run the program and use the arrow keys and the A and Z keys to navigate around our little world.

It’s surprisingly easy to add code to create “gravity.” Basically, what we’ll do is move the object downward all of the time so that the character is always moving downward (see Figure 13.1).

Figure 13.1. To create the illusion of gravity, we’ll move an object downward continually.


We will apply just a light force of gravity so that our character will still be able to jump or move off the ground but will then float gently to the ground.

If KeyDown(LEFT_KEY)=True Then x#=-0.1
If KeyDown(RIGHT_KEY)=True Then x#=0.1
If KeyDown(DOWN_KEY)=True Then y#=-0.1
If KeyDown(UP_KEY)=True Then y#=0.1
If KeyDown(Z_KEY)=True Then z#=-0.1
If KeyDown(A_KEY)=True Then z#=0.1
MoveEntity sphere,x#,y#,z#
TranslateEntity sphere, 0,-.02,0
UpdateWorld
RenderWorld
Flip
Wend
End

Take a look at the code that created the gravity:

TranslateEntity sphere, 0,-.02,0

We used the TranslateEntity command because we want the gravity to move downward on the y axis no matter what position our character is in (see Figure 13.2). The rest of the code is pretty straightforward: sphere is the name of the object we are applying gravity to, and -0.02 is the force of the gravity. We use a negative value because we want the direction of the gravity to be downward along the y axis.

Figure 13.2. The TranslateEntity command in action.


Use the TranslateEntity command rather than the MoveEntity command for the gravity so that no matter what direction the object is facing, it will always float downward.

Note: Not Too Much

Don’t make your force of gravity too high. Gravity levels that are too high will prevent your object from moving in any direction, as the downward force is too strong.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.2.111