KeyboardInput.js 1009 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. class KeyboardInput {
  2. constructor() {
  3. this.keys = [];
  4. this.press = [];
  5. this.release = [];
  6. }
  7. attach() {
  8. for (var i = 0; i < 256; i++) {
  9. this.keys[i] = false;
  10. this.press[i] = false;
  11. this.release[i] = false;
  12. }
  13. window.addEventListener("keydown", (event) => {
  14. if (!this.keys[event.keyCode]) {
  15. this.press[event.keyCode] = true;
  16. }
  17. this.keys[event.keyCode] = true;
  18. });
  19. window.addEventListener("keyup", (event) => {
  20. if (this.keys[event.keyCode]) {
  21. this.release[event.keyCode] = true;
  22. }
  23. this.keys[event.keyCode] = false;
  24. });
  25. }
  26. isPressed(code) {
  27. var pressed = this.press[code] && this.keys[code];
  28. this.press[code] = false;
  29. return pressed;
  30. }
  31. isReleased(code) {
  32. var released = this.release[code] && !this.keys[code];
  33. this.release[code] = false;
  34. return released;
  35. }
  36. isDown(code) {
  37. return this.keys[code];
  38. }
  39. }
  40. window.Keys = {
  41. Left: 37,
  42. Up: 38,
  43. Right: 39,
  44. Down: 40,
  45. W: 87,
  46. A: 65,
  47. S: 83,
  48. D: 68,
  49. Space: 32,
  50. Enter: 13,
  51. Escape: 27
  52. };