Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background-position on keypress

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- **Theme i guess-**

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.

Js fiddle

like image 297
Manoz Avatar asked Nov 17 '25 21:11

Manoz


2 Answers

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 div the area you need to show. Then with javascript you can change the position of the image either by using marginLeft or marginRight or left and right (you need to set position relative or absolute for left and right).

like image 103
otinanai Avatar answered Nov 19 '25 12:11

otinanai


When you do e.keyCode == up and the like, you can change the image source then:

if (e.keyCode == up) {
    upKey = true;
    $("#plane").attr('src', 'up-img-src');
}
like image 37
Explosion Pills Avatar answered Nov 19 '25 12:11

Explosion Pills