HTML5 Game Character Background
Working on the background for my new character. Tap near the character to make him walk.
Code
I am using BlocksJS to simplify the implementation.
<article id="walk1" class="BlocksGame"></article> <script src="js/blocksjs-0.3.5.min.js"></script>
var game, character,
element = document.getElementById("walk1"),
spec = {
width: 1080,
height: 645
};
walk = function (x, callback) {
// Stop any previous movement
character.stopMotors();
// Face the character left or right
if (x > character.x) {
character.setSlice("walkRight");
} else {
character.setSlice("walkLeft");
}
// Start walking
game.addMotor("move", {
object: character,
x: x - character.x,
speed: 2,
callback: callback || function () {
character.setSlice("stand");
}
});
};
// Create a game
game = BLOCKS.game(spec, element);
// Create the background
bg = BLOCKS.block({
layer: game.addLayer("bg"),
spec: {
slices: [{
name: "walkLeft",
imageSrc: "images/background-2.jpg"
}]
}
});
// Create the character block
character = BLOCKS.block({
layer: game.addLayer("character"),
spec: {
slices: [{
name: "walkRight",
imageSrc: "images/walk-1-right.png",
numberOfFrames: 11,
frameDelay: 1,
loop: true
}, {
name: "walkLeft",
imageSrc: "images/walk-1-left.png",
numberOfFrames: 11,
frameDelay: 1,
loop: true
}, {
name: "stand",
imageSrc: "images/stand.png"
}]
}
});
// Notify the block of game loop
game.update = function() {
bg.update();
bg.dirty = true;
character.update();
};
game.render = function() {
bg.render();
if (character.dirty) {
game.getLayer("character").clear();
}
character.render();
;
// Move the character toward tap
game.tap = function (pos) {
walk(pos.x);
};
game.start();
// Walk the character around initially
walk(200, function () {
walk(-150, function () {
walk(100);
});
});