'Touch end event- getting the touch that actually ended if there's more than one touch
I am writing a mobile movement script for a three JS app, in which if you click the upper part of the screen you rotate the camera, and the lower part you move the character. This works perfectly if you are using only one touch, but as soon as I use the second touch a problem appears: I can't seem to find a way to use the "end touch" event ONLY for the second touch- I tried using ev.touches[1] or ev.touches[0] but seems like nothing happens. I really need the device to discriminate the touch that actually ended, if it was the first one pressed, or the second one.
This is the code...
var originTouch; var secondTouch; var newTouch; var previousTouch; document.body.addEventListener('touchstart', (ev) => { originTouch = ev.touches[0]; secondTouch = ev.touches[1]; console.log(originTouch); console.log(secondTouch); }) document.body.addEventListener('touchmove', (ev) => { if (ev.touches[0]) { if (ev.touches[0].clientY > window.innerHeight / 2) { var deltaY = originTouch.clientY - ev.touches[0].clientY; var deltaX = originTouch.clientX - ev.touches[0].clientX; if (deltaY > 0) { isGoingForward = true; isGoingBackward = false;} if (deltaY < 0) { isGoingBackward = true; isGoingForward = false;} if (deltaX < 0) { isGoingRight = true; isGoingLeft = false;} if (deltaX > 0) { isGoingLeft = true; isGoingRight = false;} } else { if (previousTouch) { var movementX = ev.touches[0].pageX - previousTouch.pageX; var movementY = ev.touches[0].pageY - previousTouch.pageY; camerina.rotation.y += movementX / 400; camerina.rotation.x += movementY / 400; } previousTouch = ev.touches[0]; } } if (ev.touches[1]) { if (ev.touches[1].clientY < window.innerHeight / 2) { if (newTouch) { var movementX = ev.touches[1].pageX - newTouch.pageX; var movementY = ev.touches[1].pageY - newTouch.pageY; camerina.rotation.y += movementX / 400; camerina.rotation.x += movementY / 400; } newTouch = ev.touches[1]; } } }) document.body.addEventListener('touchend', (ev) => { //this is, of course, ending every touch when the second touch is released. //but if I use --if (ev.touches[0] or [1])-- nothing happens. //It feels like I'm not getting a way to find which is the touch that actually ended. //this has to end only if the first touch ended, isGoingForward = false; isGoingBackward = false; isGoingLeft = false; isGoingRight = false; previousTouch = null; originTouch = null; //this has to end only if the second touch ended. newTouch = null; })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
