keyboardinput.js 979 B

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