keyboardinput.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. var keyCode = event.which || event.keyCode;
  13. /*if(null != document.getElementById("chat")) {
  14. var span = document.createElement("span");
  15. var text = document.createTextNode(keyCode);
  16. span.appendChild(text);
  17. document.getElementById("chat-output").appendChild(span);
  18. }*/
  19. if(!keys[keyCode]) {
  20. press[keyCode] = true;
  21. }
  22. keys[keyCode] = true;
  23. if(keyCode == Keys.Alt || keyCode == Keys.F1) {
  24. event.preventDefault();
  25. }
  26. });
  27. window.addEventListener("keyup", function(event) {
  28. var keyCode = event.which || event.keyCode;
  29. if(keys[keyCode]) {
  30. release[keyCode] = true;
  31. }
  32. keys[keyCode] = false;
  33. if(keyCode == Keys.Alt || keyCode == Keys.F1) {
  34. event.preventDefault();
  35. }
  36. });
  37. }
  38. this.isPressed = function(code) {
  39. var pressed = press[code] && keys[code];
  40. press[code] = false;
  41. return pressed;
  42. }
  43. this.isReleased = function(code) {
  44. var released = release[code] && !keys[code];
  45. release[code] = false;
  46. return released;
  47. }
  48. this.isDown = function(code) {
  49. return keys[code];
  50. }
  51. this.clearBuffer = function() {
  52. for(var i = 0; i < 256; i++) {
  53. press[i] = false;
  54. }
  55. }
  56. };
  57. window.Keys = {
  58. Left: 37,
  59. Up: 38,
  60. Right: 39,
  61. Down: 40,
  62. W: 87,
  63. A: 65,
  64. S: 83,
  65. D: 68,
  66. I: 73,
  67. E: 69,
  68. F: 70,
  69. M: 77,
  70. T: 84,
  71. Space: 32,
  72. Enter: 13,
  73. Escape: 27,
  74. Esc: 27,
  75. Alt: 18,
  76. Shift: 16,
  77. Ctrl: 17,
  78. F1: 112
  79. };