I am new to javascript games.
I have an idea of game, As an example if I am taking Solidsnake’s character.
I want character view changes on pressing navigation keys.
If I press left key it should show left view, right key for right view and so on.
How do i get change in image on pressing keys , how can I do this in javascript?
Idea of game-

Code in brief-
var leftKey,upKey,rightKey,downKey;
var box = $("#plane"),
left = 37,
up = 38,
right = 39,
down = 40;
function key(e) {
console.log(e.keyCode);
var $key = e.keyCode;
$(document).keydown(function(e) {
if (e.keyCode == left)
leftKey = true;
if (e.keyCode == up)
upKey = true;
if (e.keyCode == right)
rightKey = true;
if (e.keyCode == down)
downKey = true;
}).keyup(function(e) {
if (e.keyCode == left)
leftKey = false;
if (e.keyCode == up)
upKey = false;
if (e.keyCode == right)
rightKey = false;
if (e.keyCode == down)
downKey = false;
});
}
$("body").keydown(function(){
key(event);
});
setInterval(function() {
if (upKey) {
box.css("top", "-=10");
}
if (rightKey) {
box.css("left", "+=10");
}
if (downKey) {
box.css("top", "+=10");
}
if (leftKey) {
box.css("left", "-=10");
}
},20);
Right now i have this code with simple navigation moves.
You can do this with CSS to set it right and avoid multiple image requests. You need to have a sprite with all images of the character in a row and then mask with a
divthe area you need to show. Then with javascript you can change the position of the image either by usingmarginLeftormarginRightorleftandright(you need to set positionrelativeorabsoluteforleftandright).