Replace hammer with touch event handling
[2048.git] / js / keyboard_input_manager.js
blob:a/js/keyboard_input_manager.js -> blob:b/js/keyboard_input_manager.js
--- a/js/keyboard_input_manager.js
+++ b/js/keyboard_input_manager.js
@@ -57,20 +57,31 @@
   retry.addEventListener("click", this.restart.bind(this));
 
   // Listen to swipe events
-  var gestures = [Hammer.DIRECTION_UP, Hammer.DIRECTION_RIGHT,
-                  Hammer.DIRECTION_DOWN, Hammer.DIRECTION_LEFT];
-
+  var touchStartClientX, touchStartClientY;
   var gameContainer = document.getElementsByClassName("game-container")[0];
-  var handler       = Hammer(gameContainer, {
-    drag_block_horizontal: true,
-    drag_block_vertical: true
+  gameContainer.addEventListener("touchstart", function(event) {
+    if (event.touches.length > 1) {
+      return;
+    }
+    touchStartClientX = event.touches[0].clientX;
+    touchStartClientY = event.touches[0].clientY
+    event.preventDefault();
   });
-  
-  handler.on("swipe", function (event) {
-    event.gesture.preventDefault();
-    mapped = gestures.indexOf(event.gesture.direction);
-
-    if (mapped !== -1) self.emit("move", mapped);
+  gameContainer.addEventListener("touchmove", function(event) {
+    event.preventDefault();
+  });
+  gameContainer.addEventListener("touchend", function(event) {
+    if (event.touches.length > 0) {
+      return;
+    }
+    var dx = event.changedTouches[0].clientX - touchStartClientX;
+    var absDx = Math.abs(dx);
+    var dy = event.changedTouches[0].clientY - touchStartClientY;
+    var absDy = Math.abs(dy);
+    if (Math.max(absDx, absDy) > 10) {
+      self.emit("move", absDx > absDy ? (dx > 0 ? 1 : 3) : 
+        (dy > 0 ? 2 : 0)); // (right : left) : (down : up)
+    }
   });
 };
 

comments