What is the best way to handle multiple key events in Javascript?

前端 未结 4 2119
半阙折子戏
半阙折子戏 2021-02-08 11:24

Pressing space bar in game will make a character shoot, pressing space bar when a confirmation box is shown will make this box disappear and pressing space bar in a highscore fo

4条回答
  •  轮回少年
    2021-02-08 11:57

    you could instead add and remove the event listener as needed.

    let's assume you're using a javascript framework (if you're not, then you probably should be considering the amount of JS code involved in a game like this)

    using PrototypeJS:

    when game starts,

    document.observe("keydown",shootHandler());
    

    when the message box is created,

    function createBox(text) {
        ...snip
    
        document.observe("keydown",closeBox());
        document.fire("game:pause");
    }
    

    and, for example

    var paused = false;
    
    function shoothandler() {
       if (!paused) {
           alert("pew! pew!");
       }
    }
    
    function closeBox() {
        $('messagebox').remove();
        document.fire("game:unpaused");
        document.stopObserving("keydown",closeBox());
    }
    
    document.observe("game:paused", function() { paused = true;});
    document.observe("game:unpaused", function() { paused = false;});
    document.observe("game:over", function() { document.stopObserving("keydown",shootHandler());});
    

    I haven't included the high score screen but the theory is the same.

    As you can see, I also used custom events to notify the pause status. The same event could also be fire by a puase button in the interface, etc...

提交回复
热议问题