Thursday, March 22, 2012

JavaScript Animation: Taking it Further


Game in action.

This post builds on the work done in the previous post, extending the concept into a game.

The game consists of a ball placed on a desk. The objective is to roll the ball to the bin, using enough power, but not too much.

Preparing the Images

As in the previous post, an image of a ball was created, and rotated three times, giving four separate images. By using the Phi Phenomenon, cycling through the four images quickly enough will give the impression of movement.

Additionally, images of a desk and a bin were needed. The desk was found here*, and the bin was found here*.

Image resources used. Click to zoom.

Game Mechanics

The game is simple.

  1. The ball is placed on top of the desk.
  2. The bin is placed towards the bottom-right of the desk in a random position along the "ground".
  3. The user has to judge how far the bin is from the desk, and select an appropriate power value (1 to 5) from a slider.

Here is a screenshot of all the elements lined up.

Game in action. Click to zoom.

HTML5 Slider

To allow the user to select the power, an HTML5 range element is used as part of the form. Additionally, a number next to the slider is used to indicate to the user the power that they have selected.

<input type="range" name="power" id="power" 
value="1" min="1" max="5" style="max-width:75px;" onChange="showAndSetPower(this.value);"> <span id="powerDisplay">1</span>

Below is the JavaScript function called showAndSetPower(), which will provide feedback to the user and set the power value internally.

function showAndSetPower(newVal) {
    document.getElementById("shotPos").innerHTML = 540+(newVal*20);
    powerVal = newVal;

Unfortunately, in non-webkit browsers the range element is not supported. This means that, as it stands today, the document will only render properly in Apple Safari or Google Chrome. Opera was untested. If your browser supports it, the above code results in the following:

Power: 1


Here is a video demonstration of the game in action.

You can view a live version of the JavaScript game. Click the big button below:

Note: becuase of the fact that HTML5 is best viewed on either Apple Safari or Google Chrome, I can only recommend that you view and play the game in either of those browsers.

Download Source Code

I've made the source code available at this Pastebin, where you can easily view and download my source code.

It's also embedded below.

No comments:

Post a Comment