user1580096
user1580096

Reputation: 487

Asynchronous Keypress EventHandler in Javascript

I am developing a small enemy plane shooter game using HTML5 and Javascript. In the game I implemented the bulletFiring of the shooter plane using the EventHandler of keypress and then I am using the setInterval method to periodically change the look of the canvas where the bullets are drawn. So in the game while I am moving the plane up and down and then pressing the fire key the plane stops moving(both keys pressed simultaneously).

function move(e)
{
    if(e.keyCode==40)
    {
        //Move the jet down
    }
    else if(e.keyCode==38)
    {
        //Move the Jet Up
    }
    else if(e.keyCode==32)//Space Bar
    {
        //Fire the bullet
    }
}

So when I press both SPACE and UP keys then space key event-handler is occurring but not of the UP key and the plane stops moving. Can someone help me how to keep both events in parallel so that one does not stop the other from happening.

Upvotes: 0

Views: 1737

Answers (1)

robert.bo.roth
robert.bo.roth

Reputation: 1353

Like Brian said, you should take a look at this solution.

Another thing to keep in mind is that you may need to keep track of all keys that are currently being pressed. That being said, if you move your move() function into the keyup event, you'll be testing off of your tracking array rather than the e.keyCode of the key that was just released.

e.g.

function move(e)
{
    if(keysDown[40])
    {
        //Move the jet down
    }
    else if(keysDown[38])
    {
        //Move the Jet Up
    }
    else if(keysDown[32])//Space Bar
    {
        //Fire the bullet
    }

    // RESET TRACKING WHEN KEY IS RELEASED
}

var keysDown = {};      // Tracking object

$("body").on('keydown', function(e) {
    keysDown[e.keyCode] = true;
});

$("body").on('keyup', function(e) {
    keysDown[e.keyCode] = false;
});

With something like this, you'll have to call your move() function from within your setInterval function.

Upvotes: 1

Related Questions