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?
Asked
Active
Viewed 1.5k times
2
-
You could consider a library such as [HammerJS](https://hammerjs.github.io/) – Alexander Staroselsky Nov 07 '18 at 15:22
1 Answers
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
-
1While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Luca Kiebel Nov 07 '18 at 15:27
-
-
2
-