切换到按钮控制游戏而不是键盘

时间:2014-05-26 19:24:02

标签: javascript html5 keyboard

我正在用html5和java构建一个简单的浏览器游戏。最初我用键盘管理游戏控制,现在我试图将控制从键盘切换到按钮,但似乎没有任何效果。我不知道如何做出正确的方法。这是我的键盘控件代码:

//Keyboard controls
    document.onkeydown = function(e) {
        var key = e.keyCode;

        if (key == 37) {
            dir = "left";
            player.isMovingLeft = true;
        } else if (key == 39) {
            dir = "right";
            player.isMovingRight = true;
        }

        if(key == 32) {
            if(firstRun === true) {
                init();
                firstRun = false;
            }
            else 
                reset();
        }
    };

我的按钮代码不正常:

document.onclick = function(e) {
            var onclick = e.clickEvent;

            if (onclick = "btn1") {
                dir = "left";
                player.isMovingLeft = true;
            } else if (onclick = "btn2") {
                dir = "right";
                player.isMovingRight = true;
            }
        };

在此先感谢,感谢每一位帮助!

1 个答案:

答案 0 :(得分:0)

你需要这样的东西:

document.onclick = function(e) {
        var onclick = e.target.id; // e.target gets the element which originally triggered the event

        if (onclick == "btn1") { // watch out for == instead of =
            dir = "left";
            player.isMovingLeft = true;
        } else if (onclick == "btn2") {
            dir = "right";
            player.isMovingRight = true;
        }
};