移动物体时,如何最好地组合方向移动(向上和向左,向上和向右......)?

时间:2014-01-13 16:05:35

标签: javascript keyboard-events easeljs

我在Javascript中使用EaselJS,我使用keydownkeyup事件来捕获键盘输入(见下文):

/*Connecting keydown input to keyPressed handler*/
this.document.onkeydown = keyPressed;
/*Connecting key up event to keyUp handler*/
this.document.onkeyup = keyUp;

我按下以下代码来捕捉向上,向左和/或向右按下,并暂时对它们作出反应。这个运动现在很破旧,我还在努力改进它。为了能够正确移动我的物体,我应该能够同时捕捉角度变化(左/右)和加速(前进)。

这是我目前使用的keyDown代码:

    /*Keyboard input handlers - keydown and keyup*/
    function keyPressed(event){
        if(!event){ var event = window.event; }
        switch(event.keyCode){
            case KEYCODE_LEFT: 
                console.log("left held");
                ellip.x -= 5;
                break;
            case KEYCODE_RIGHT: 
                console.log("right held");
                ellip.x += 5; 
                break;
            case KEYCODE_UP: 
                console.log("up held");
                ellip.y -= 5;
                break;
            case KEYCODE_DOWN: 
                console.log("down held");
                ellip.y += 5;
                break;          
        }
    }

现在注意到在控制台中点击两个箭头按钮不会产生消息组合(例如up heldright held

我如何处理(或收听)多个事件?

Here is a Fiddle!使用上,下,左,右箭头移动红斑。

1 个答案:

答案 0 :(得分:2)

处理此问题的方法是捕获keyDown代码中的哪些键,然后在handleTick函数中进行移动。您还需要查看keyUp,以便知道密钥何时不再关闭:

/*Keyboard input handlers - keydown and keyup*/
var left,
    right,
    up,
    down;

function keyPressed(event){
    if(!event){ var event = window.event; }
    switch(event.keyCode){
        case KEYCODE_LEFT: 
            console.log("left held");
            left = true;
            break;
        case KEYCODE_RIGHT: 
            console.log("right held");
            right = true; 
            break;
        case KEYCODE_UP: 
            console.log("up held");
            up = true;
            break;
        case KEYCODE_DOWN: 
            console.log("down held");
            down = true;
            break;          
    }
}

function keyReleased(event){
    if(!event){ var event = window.event; }
    switch(event.keyCode){
        case KEYCODE_LEFT: 
            console.log("left released");
            left = false;
            break;
        case KEYCODE_RIGHT: 
            console.log("right released");
            right = false; 
            break;
        case KEYCODE_UP: 
            console.log("up released");
            up = false;
            break;
        case KEYCODE_DOWN: 
            console.log("down released");
            down = false;
            break;          
    }
}

function handleTick(event){
    /*Scaling down the image*/
    ellip.scaleX = 0.10;
    ellip.scaleY = 0.10;

    if(left) {
        ellip.x -= 5;
    } else if(right) {
        ellip.x += 5;
    }

    if(up) {
        ellip.y -= 5;
    } else if(down) {
        ellip.y += 5;
    }

    if (ellip.x > stage.canvas.width) { 
        ellip.x = stage.canvas.width; 
    }   
    stage.update();
}

编辑:在行动中分叉:http://jsfiddle.net/t2M82/