(not tested on iOS / Windows phone)
I'm building an HTML5 game for mobile and want to use the user's touch input as a joystick/controler but every touchmove scripts I found out there seem to break after a prolonged touchmove. I've only properly tested this on android devices but I've tried several different browsers and the results are the same. I know of e.preventdefault
and width=device-width
and I am using both but this bug still occurs. Here's the code I'm using:
function initInput()
{
canvas = document.getElementById("Canvas");
canvas.addEventListener("mousedown",mouseDown, false);
canvas.addEventListener("mouseup", mouseUp, false);
canvas.addEventListener("mousemove",mouseXY, false);
canvas.addEventListener("touchstart", touchDown, false);
canvas.addEventListener("touchend", touchUp, false);
canvas.addEventListener("touchcancel", touchUp, false);
canvas.addEventListener("touchleave", touchUp, false);
canvas.addEventListener("touchmove", touchXY, false);
}
function mouseUp(e)
{
e.preventDefault();
mouseIsDown = 0;
}
function touchUp(e)
{
e.preventDefault();
mouseIsDown = 0;
}
function mouseDown(e)
{
e.preventDefault();
mouseIsDown = 1;
touchInitX = e.pageX - canvas.offsetLeft;
touchInitY = e.pageY - canvas.offsetTop;
}
function touchDown(e)
{
e.preventDefault();
mouseIsDown = 1;
var touch = e.targetTouches[0];
if (e.touches)
{
if (e.touches.length == 1)
{
touchInitX = touch.pageX - touch.target.offsetLeft;
touchInitY = touch.pageY - touch.target.offsetTop;
}
}
}
function mouseXY(e)
{
e.preventDefault();
canvasX = e.pageX - canvas.offsetLeft;
canvasY = e.pageY - canvas.offsetTop;
}
function touchXY(e) {
e.preventDefault();
var touch = e.targetTouches[0];
if (e.touches) {
if (e.touches.length == 1)
{
canvasX = touch.pageX - canvas.offsetLeft;
canvasY = touch.pageY - canvas.offsetTop;
}
}
}
And here are a few examples where you can test this behavior happening:
http://www.onlywebpro.com/demo/gamedev/mouse_detect.html
These are different approaches/scripts I found on the web and so far all touchmove code examples I found out there none seems to work properly. If you simulate a continuous dragging on android devices touchmove will break at some point and return a touchend followed by a touchstart continuously until you release your finger to stop the touchmove. This can take 1 second or a couple of minutes but touchmove will always break at some point.
Any suggestions/solutions would be appreciated.