How to Add Realistic Motion to Your HTML5 Game

By Andy Harris

Take a look at space.html. This simple game provides a good example for applying realistic motion to your HTML5 game. It utilizes the control scheme made famous in the classic games Asteroids and Spacewar! (Though Asteroids is better-known, Spacewar! is by far the earlier and more influential game.)


Click here to get the full experience.

How to add a force vector to your game’s object

The ship is controlled by the arrow keys, but Newton’s effect is easier to see in space than on the ground (no pesky drag forces to get in the way). The left- and right-arrow keys rotate the ship, but they do not affect the ship’s motion. The up arrow fires a rocket, which adds a force vector in the direction the ship is currently facing.

Here’s the code:

<html lang="en-US">
 <meta charset="UTF-8">
 <script type="text/javascript"
   src = "simpleGame.js"></script>
 <script type="text/javascript">
 var ship;
 var game;
 function Ship(){
  tShip = new Sprite(game, "ship.png", 25, 25);
  tShip.checkKeys = function(){
   if (keysDown[K_LEFT]){
   if (keysDown[K_RIGHT]){
   if (keysDown[K_UP]){
    this.addVector(this.getImgAngle(), .1);
  } // end function
  return tShip;
 } // object definition
 function init(){
  game = new Scene();
  ship = new Ship(); 
 } // end init
 function update(){
 } // end update
<body onload = "init()">

How to simulate space in your game

Here’s the rundown:

  1. Begin the example in the normal way.

    Like most simpleGame demos, begin with a sprite and a scene. Because the ship will have a custom method, you make it a unique object.

  2. Give the ship a checkKeys() method.

    The checkKeys() method looks for key presses and changes the ship’s behavior accordingly.

  3. Change the image angle.

    A sprite actually has two distinct angles. It can have an angle that it’s pointing (called the imgAngle in simpleGame) and the angle it’s moving (called the moveAngle). When you change the angle, you’re changing both the movement and the image angles on the assumption that the object will simply travel in the direction it’s facing.

    For simple examples this is fine, but many kinds of motion require decoupling the image and motion angles. The changeImgAngleBy() method allows you to change the direction the image is pointing without changing the motion angle. (There is a changeMotionAngle() method, too, but it isn’t used very often.)

  4. Add a force vector to simulate thrust.

    When the user presses the up arrow, the ship fires its main rockets. This adds a small force vector in the direction the ship is currently facing. Use the getImgAngle() method to determine the direction the ship is currently facing, and use this value to specify where the force should be added.

    Because this code is happening in the animation loop and is amplified as the arrow key is held down, only a very small force is needed.