Browse Source

Gamepad is working for jumps.

Dennis Guse 5 years ago
parent
commit
c09b1b727e
1 changed files with 30 additions and 0 deletions
  1. 30 0
      js/game.js

+ 30 - 0
js/game.js

@@ -68,6 +68,8 @@ function Runner(outerContainerId, opt_config) {
   // } else {
     this.loadImages();
   // }
+
+  this.gamepadPreviousKeyDown = false;
 }
 window['Runner'] = Runner;
 
@@ -597,6 +599,34 @@ Runner.prototype = {
       document.addEventListener(Runner.events.MOUSEUP, this);
     }
     window.addEventListener(Runner.events.GAMEPADCONNECTED, this);
+    window.setInterval(this.pollGamepads.bind(this), 10);
+  },
+
+  /**
+   * Convert Gamepad input events to keydown/up events (spacebar)
+  */
+  pollGamepads: function() {
+    var gamepads = navigator.getGamepads();
+    var keydown = false;
+    for(var i = 0; i < gamepads.length; i++) {
+      if (gamepads[i] != undefined) {
+        if (gamepads[i].buttons.filter(function(e){return e.pressed == true}).length > 0) {
+          keydown = true;
+        }
+      }
+    }
+    if (keydown != this.gamepadPreviousKeyDown) {
+      this.gamepadPreviousKeyDown = keydown;
+
+      var event = new Event(keydown ? 'keydown' : 'keyup');
+      event.keyCode = 32;//keys(Runner.keycodes.JUMP)[0];
+      event.which = event.keyCode;
+      event.altKey = false;
+      event.ctrlKey = true;
+      event.shiftKey = false;
+      event.metaKey = false;
+      document.dispatchEvent(event);
+    }
   },
 
   /**