有時做原生遊戲時,特別是Android平臺需要監聽返回鍵,在遊戲中做出迴應如返回遊戲上一層或者是退出遊戲。
實現
- 監聽事件
//android 返回鍵
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
- 取消事件
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
- 回調處理
onKeyDown(event) {
switch (event.keyCode) {
//注意Creator版本爲2.x的請把cc.KEY.back。修改成cc.macro.KEY.back
case cc.KEY.back:
if (this.isBackGame) {
cc.director.end();
return;
}
this.isBackGame = true;
this.label.string = '再次按返回鍵\n將退出遊戲';
this.node.runAction(cc.sequence(cc.delayTime(3), cc.callFunc(() => {
this.isBackGame = false;
this.label.string = '';
})));
break;
}
},
完整代碼
cc.Class({
extends: cc.Component,
properties: {
label: {
default: null,
type: cc.Label
},
text: 'Hello, World!'
},
// use this for initialization
onLoad: function () {
this.label.string = this.text;
this.registerEvent();
},
registerEvent() {
//android 返回鍵
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
},
onKeyDown(event) {
switch (event.keyCode) {
//注意Creator版本爲2.x的請把cc.KEY.back。修改成cc.macro.KEY.back
case cc.KEY.back:
if (this.isBackGame) {
cc.director.end();
return;
}
this.isBackGame = true;
this.label.string = '再次按返回鍵\n將退出遊戲';
this.node.runAction(cc.sequence(cc.delayTime(3), cc.callFunc(() => {
this.isBackGame = false;
this.label.string = '';
})));
break;
}
},
offEvent() {
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
},
// called every frame
update: function (dt) {
},
onDestroy() {
this.offEvent();
}
});
關於cc.systemEvent
它是系統事件,systemEvent目前支持按鍵事件和重力感應事件。詳情官方文檔。
關於cc.KEY修改成cc.macro.KEY的問題
詳情請點擊這
最後
如果對你有用,請點喜歡哦。最後放出Demo給大家參考。