How to Add Gravity to Your HTML5 Game
Gravity calculations have been a part of HTML5 video games from the very beginning. There are actually two kinds of gravity to consider. In platform-style games, the player is close to a planet, and all gravity appears to pull everything straight down.
When you know how to add acceleration vectors, platform-style gravity is actually easy to work with. Think of gravity as a constant force always pulling down a small amount every frame.
How to add rockets to your game’s ride
This example has one other interesting feature. When you press the up arrow, the car image is changed to another image with flames.
The code for the hoverCar example is shown here in its entirety:
How to use force vector in your game
Gravity is actually pretty straightforward. It’s simply a force vector. The other interesting parts of this example involve changing the horizontal motion without changing the car’s image angle and adjusting the image to indicate the thruster. Here are the steps:
Build two different images.
Use your image editor to build two different versions of the image.
Build an ordinary sprite.
Like most vehicle sprites, you need a checkKeys() method. This one is set up in the ordinary way, but the behavior is a bit different.
Set the image to default.
The default image has no thrusters. Use the changeImage() method to make this the default image. When the thrusters are turned on, the image will be changed.
Use a variable to control horizontal speed.
You can create the hSpeed variable to manage the horizontal speed of the car.
Set the left and right arrows to modify hSpeed.
The left and right arrow keys modify the hSpeed variable.
Use changeXby to set the horizontal speed.
After checking all the keys, change the x value of the car to the current value of hSpeed.
The up arrow adds a vector upward.
Use the now-infamous addVector() function to add a small force vector upward when the user presses the up arrow. Remember that 0 degrees is up. Play around with this value to get the amount of thrust you want for your game.
Show the thrusters when the up arrow is pressed.
If the user is pressing the up arrow, you need to show the thrusters. Use the changeImage() method to set the sprite’s image to the one with rocket thrusters.
Build a checkGravity() method.
This method will be called every frame to compensate for gravity.
Check to see if you’re on the ground.
In this example, the ground is defined as a y value larger than 580.
If you’re not on the ground, add a gravity force vector.
Because it will accumulate, the gravity force vector needs to be pretty small. You’ll need to balance the force of the gravity and the thrusters to get the behavior you want. If gravity is too strong, the thrusters won’t work. If thrusters are too strong, the car simply flies into space.