Cocos2d-JS鍵盤事件

來源:互聯網
上載者:User

Cocos2d-JS鍵盤事件
Cocos2d-JS中的鍵盤事件與觸摸事件不同,它沒有空間方面資訊。鍵盤事件不僅可以響應鍵盤,還可以響應裝置的菜單。
鍵盤事件是EventKeyboard,對應的鍵盤事件監聽器(cc.EventListener.KEYBOARD),鍵盤事件響應屬性:
onKeyPressed。當鍵按下時回調該屬性所指定函數。
onKeyReleased。當鍵抬起時回調該屬性所指定函數。
使用鍵盤事件處理的程式碼片段如下:

onEnter: function () {    this._super();    cc.log(HelloWorld onEnter);        cc.eventManager.addListener({①    event: cc.EventListener.KEYBOARD, ②    onKeyPressed:  function(keyCode, event){ ③    cc.log(Key with keycode  + keyCode +  pressed);    },    onKeyReleased: function(keyCode, event){ ④    cc.log(Key with keycode  + keyCode +  released);    }    }, this);    },    onExit: function () {    this._super();    cc.log(HelloWorld onExit);    cc.eventManager.removeListeners(cc.EventListener.KEYBOARD);⑤    }
上述代碼第①行cc.eventManager.addListener是通過捷徑註冊事件監聽器對象。第②行代碼是設定鍵盤事件cc.EventListener.KEYBOARD。第③行代碼是設定鍵盤按下屬性onKeyPressed,其中的參數keyCode是按下的鍵編號。第④行代碼是設定鍵盤抬起屬性onKeyReleased。
上述onExit()函數是退出層時候回調,我們在代碼第⑤行登出所有鍵盤事件的監聽。
我們可以使用Cocos Code IDE和WebStorm工具進行測試,輸出的結果如下:
JS: Key with keycode 124 releasedJS: Key with keycode 124 pressedJS: Key with keycode 139 pressedJS: Key with keycode 139 releasedJS: Key with keycode 124 releasedJS: Key with keycode 139 pressedJS: Key with keycode 124 pressedJS: Key with keycode 139 releasedJS: Key with keycode 124 releasedJS: Key with keycode 139 pressedJS: Key with keycode 124 pressedJS: Key with keycode 139 releasedJS: Key with keycode 124 released

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.