Game Development Reference
In-Depth Information
Other elements only add to the experience, either visually (through animations and
other visual components) or with more interaction. But these are the basic game
components without which the game cannot work.
JavaScript and logic
The logic for this game is separated into three very basic components, namely, a
Player class that encapsulates the behavior of each player, a game loop function
that is called at a regular interval based on a game timer, and a few global functions
that encapsulate various pieces of logic used throughout the life cycle of the applic-
ation.
The Player class holds a reference to the DOM nodes that represent the player, the
track where the player runs, and defines some basic behavior to control the player.
function Player(query) {
// Hold a reference to the DOM element that
they playerwill control
var element = document.querySelector(query);
var trackWidth =
parseInt(element.parentElement.offsetWidth);
var minLeft = 0 -
parseInt(element.offsetWidth / 2);
var maxLeft = trackWidth -
parseInt(element.offsetWidth / 2);
// Move the player based on whatever speed is
set inits custom data attribute
this.move = function() {
var left = parseInt(element.style.left);
var speed =
parseInt(element.attributes.getNamedItem("data-speed").value);
element.style.left = (left + speed) + "px";
if (left > maxLeft) {
this.moveToFinish();
Search WWH ::




Custom Search