JavaScript游戏KeyDown事件&键盘操作不起作用

时间:2014-08-01 10:08:19

标签: javascript

我目前正在学习JavaScript,并且在我继续学习之前一直试图组建一个简单的游戏。我的游戏中有一些区域需要适应...但我主要关注的是为什么我的KeyDown事件(带有额外的箭头键盘输入)没有响应。我已经在线跟踪了几个例子,从我看到的情况来看,它应该正常工作......

以下是相关的代码:

            //player (keyboard) input
            var keysDown= {};

            document.addEventListener("keyDown", function(e) {
                console.log('key press');
                keysDown[e.keyCode] = true;
            }, false);

            document.addEventListener("keyUp", function(e) {
                delete keysDown[e.keyCode];
            }, false);

            //updating game objects + keysDown event
            var update = function (modifier) {

                if(38 in keysDown) {
                    interObject.y -= interObject.speed * modifier;
                }
                if(40 in keysDown) {
                    interObject.y += interObject.speed * modifier;
                }
                if(37 in keysDown) {
                    interObject.x -= interObject.speed * modifier;
                }
                if(39 in keysDown) {
                    interObject.x += interObject.speed * modifier;
                }

                if (
                    interObject.x === catchObject.x
                    && catchObject.x === interObject.x
                    && interObject.y === catchObject.y
                    && catchObject.y === interObject.y 
               ) {
               ++catchObjectCaught;
               rest();
               }
            };

1 个答案:

答案 0 :(得分:1)

我认为你不小心把你的'keyDown'等大写了,请看小提琴:

http://jsfiddle.net/u827H/1/

document.addEventListener("keydown", function(e) {
    alert('works')
}, false);

document.addEventListener("keyDown", function(e) {
    alert('wont ever see this')
}, false);

他们都应该是小写'keydown','keyup'