KeyBoardControl.ts 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import BasicObject from "../../../Engine/Basic/BasicObject";
  2. import EventManager from "../../../Engine/Event/EventManager";
  3. import GameManager from "../../Game/GameManager";
  4. import { CMD } from "../../SDK/sdk";
  5. /**
  6. * 键盘操作组件
  7. */
  8. export default class KeyBoardControl extends BasicObject {
  9. /**键盘值记录 */
  10. private codes: Map<number, number>;
  11. constructor () {
  12. super();
  13. this.codes = new Map<number, number>();
  14. cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
  15. cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
  16. }
  17. _destroy () {
  18. cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
  19. cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
  20. super._destroy();
  21. }
  22. onKeyDown (event) {
  23. let bool = true;
  24. switch(event.keyCode) {
  25. case cc.macro.KEY.left:
  26. this.codes.set(cc.macro.KEY.left, cc.macro.KEY.left);
  27. this.codes.delete(cc.macro.KEY.right);
  28. break;
  29. case cc.macro.KEY.right:
  30. this.codes.set(cc.macro.KEY.right, cc.macro.KEY.right);
  31. this.codes.delete(cc.macro.KEY.left);
  32. break;
  33. case cc.macro.KEY.up:
  34. this.codes.set(cc.macro.KEY.up, cc.macro.KEY.up);
  35. this.codes.delete(cc.macro.KEY.down);
  36. break;
  37. case cc.macro.KEY.down:
  38. this.codes.set(cc.macro.KEY.down, cc.macro.KEY.down);
  39. this.codes.delete(cc.macro.KEY.up);
  40. break;
  41. case cc.macro.KEY.z:
  42. bool = !this.codes.has(cc.macro.KEY.z);
  43. this.codes.set(cc.macro.KEY.z, cc.macro.KEY.z);
  44. break;
  45. }
  46. if (bool == true) {
  47. this.sendJoystickEvent();
  48. }
  49. }
  50. onKeyUp (event) {
  51. this.codes.delete(event.keyCode);
  52. this.sendJoystickEvent();
  53. }
  54. private sendJoystickEvent (): void {
  55. this.codes.forEach((value: number, key: number) => {
  56. switch(value) {
  57. case cc.macro.KEY.left:
  58. EventManager.sendEvent(CMD.ENTER_KEY.toString());
  59. break;
  60. case cc.macro.KEY.right:
  61. EventManager.sendEvent(CMD.CANCLE_KEY.toString());
  62. break;
  63. case cc.macro.KEY.up:
  64. EventManager.sendEvent(CMD.BACK_LEFT.toString());
  65. break;
  66. case cc.macro.KEY.down:
  67. EventManager.sendEvent(CMD.BACK_RIGHT.toString());
  68. break;
  69. case cc.macro.KEY.z:
  70. EventManager.sendEvent(GameManager.ActionEvent);
  71. break;
  72. }
  73. });
  74. }
  75. }