2

I want to make simple game in js. But for that I want to user play by swiping finger/cursor on the screen, up / down / right / left. There is a simple way to make that?

MMon
  • 155
  • 1
  • 1
  • 10

1 Answers1

22

You can try this. Very simple and easy to understand.

  var container = document.querySelector("CLASS OR ID FOR WHERE YOU WANT TO DETECT SWIPE");

  container.addEventListener("touchstart", startTouch, false);
  container.addEventListener("touchmove", moveTouch, false);

  // Swipe Up / Down / Left / Right
  var initialX = null;
  var initialY = null;

  function startTouch(e) {
    initialX = e.touches[0].clientX;
    initialY = e.touches[0].clientY;
  };

  function moveTouch(e) {
    if (initialX === null) {
      return;
    }

    if (initialY === null) {
      return;
    }

    var currentX = e.touches[0].clientX;
    var currentY = e.touches[0].clientY;

    var diffX = initialX - currentX;
    var diffY = initialY - currentY;

    if (Math.abs(diffX) > Math.abs(diffY)) {
      // sliding horizontally
      if (diffX > 0) {
        // swiped left
        console.log("swiped left");
      } else {
        // swiped right
        console.log("swiped right");
      }  
    } else {
      // sliding vertically
      if (diffY > 0) {
        // swiped up
        console.log("swiped up");
      } else {
        // swiped down
        console.log("swiped down");
      }  
    }

    initialX = null;
    initialY = null;

    e.preventDefault();
  };

Reference: https://www.kirupa.com/html5/detecting_touch_swipe_gestures.htm

Mahbub Hasan
  • 391
  • 3
  • 5