How to Use the Reset Method for Your HTML5 Game - dummies

How to Use the Reset Method for Your HTML5 Game

By Andy Harris

When two objects collide in your HTML5 game, it often means something important. This is where the reset method comes in. You’ll often want to change the score, play a sound, reduce the number of lives, or something. However, if those objects are moving slowly, they could overlap for multiple turns.

Generally, game programmers avoid this by applying a simple rule: When two things collide, move or kill one of them. For this particular application, the fly gets eaten by the frog, and a new fly appears. Of course, that’s just an illusion. The same fly gets recycled and simply appears in a new space.

You can see the fly.reset() method call in the update() function, but now you need to add that method to the fly’s definition in frogLib.js. Take a look at the final version of the Fly class:

function Fly(){
 tFly = new Sprite(scene, "fly.png", 20, 20);
 tFly.wriggle = function(){
  //change direction by some random amount
  newDir = (Math.random() * 90) - 45;
 } // end wriggle
 tFly.reset = function(){
  //set new random position
  newX = Math.random() * this.cWidth;
  newY = Math.random() * this.cHeight;
  this.setPosition(newX, newY);
 } // end reset
 return tFly;
} // end Fly

The reset() method applies a new random position to the fly. Here’s how it works:

  1. Generate a random number between 0 and 1.

    The Math.random() function built into JavaScript does this.

  2. Multiply that value by the canvas width.

    The canvas width is stored in each sprite’s cWidth property.

  3. Set the sprite’s x value to the resulting random number.

    This generates a random value between 0 and the width of the screen.

  4. Repeat for the y value.

    Calculate a new Y position in the same way, but this time multiply by the sprite’s cHeight property.

  5. Reset the temporary fly before returning it.

    If you call the fly’s reset() method before returning it, you guarantee that the fly begins in a random position.