import BasicObject from "../../../Engine/Basic/BasicObject"; import EventManager from "../../../Engine/Event/EventManager"; import GameManager from "../../Game/GameManager"; import { CMD } from "../../SDK/sdk"; /** * 键盘操作组件 */ export default class KeyBoardControl extends BasicObject { /**键盘值记录 */ private codes: Map; constructor () { super(); this.codes = new Map(); cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this); cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this); } _destroy () { cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this); cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this); super._destroy(); } onKeyDown (event) { let bool = true; switch(event.keyCode) { case cc.macro.KEY.left: this.codes.set(cc.macro.KEY.left, cc.macro.KEY.left); this.codes.delete(cc.macro.KEY.right); break; case cc.macro.KEY.right: this.codes.set(cc.macro.KEY.right, cc.macro.KEY.right); this.codes.delete(cc.macro.KEY.left); break; case cc.macro.KEY.up: this.codes.set(cc.macro.KEY.up, cc.macro.KEY.up); this.codes.delete(cc.macro.KEY.down); break; case cc.macro.KEY.down: this.codes.set(cc.macro.KEY.down, cc.macro.KEY.down); this.codes.delete(cc.macro.KEY.up); break; case cc.macro.KEY.z: bool = !this.codes.has(cc.macro.KEY.z); this.codes.set(cc.macro.KEY.z, cc.macro.KEY.z); break; } if (bool == true) { this.sendJoystickEvent(); } } onKeyUp (event) { this.codes.delete(event.keyCode); this.sendJoystickEvent(); } private sendJoystickEvent (): void { this.codes.forEach((value: number, key: number) => { switch(value) { case cc.macro.KEY.left: EventManager.sendEvent(CMD.ENTER_KEY.toString()); break; case cc.macro.KEY.right: EventManager.sendEvent(CMD.CANCLE_KEY.toString()); break; case cc.macro.KEY.up: EventManager.sendEvent(CMD.BACK_LEFT.toString()); break; case cc.macro.KEY.down: EventManager.sendEvent(CMD.BACK_RIGHT.toString()); break; case cc.macro.KEY.z: EventManager.sendEvent(GameManager.ActionEvent); break; } }); } }