Question

Space Invader game: I want to control the 'base gun' (move it left and right and fire missiles at the invaders. So I need a keypress or (keydown?) event to change a variable (x coordinate) and a key press event to fire a missile.

Can anyone show me how the keypress event is detected and the variable is changed?

Was it helpful?

Solution

document.onkeydown = function(e) {
        var key = e.keyCode;
        if (key===37) {//left arrow pressed

        } else if (key===39) {//right arrow pressed

        }

}

OTHER TIPS

Like this?

document.onkeydown = checkKey;

var xCoord = 100;

function checkKey(e) {
    e = e || window.event;

    switch (e.keyCode) {
        case 37 : // left
            xCoord -= 5;
        break;
        case 39 : // right
            xCoord += 5;
        break;
    }
}

Exciting fiddle: http://jsfiddle.net/u5eJp/

Couple things I would like to add to the other answers:

1) Use constants to make it easier on yourself

2) There is no way to check if a key is currently pressed in javascript, so you should keep track of what is currently pressed as well

var pressed = {
    up: false,
    down: false,
    left: false,
    right: false
};

var LEFT_ARROW = 37;
var UP_ARROW = 38;
var RIGHT_ARROW = 39;
var DOWN_ARROW = 40;

document.onkeydown = function (e) {
    e = e || window.event;
    switch (e.keyCode) {
    case LEFT_ARROW:
        pressed.left = true;
        break;
    case UP_ARROW:
        pressed.up = true;
        break;
    case RIGHT_ARROW:
        pressed.right = true;
        break;
    case DOWN_ARROW:
        pressed.down = true;
        break;
    default: 
        break;
    }
}

//update position separately
function updatePos() {
    if (pressed.up) { //change y up }
    if (pressed.down) { //change y down }
    if (pressed.left) { //change x left }
    if (pressed.right) { //change x right }
}

Hope this helps, and good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top