(未在 iOS / Windows 手机上测试)
我正在为移动设备构建 HTML5 游戏,并希望将用户的触摸输入用作操纵杆/控制器,但我在那里发现的每个 touchmove 脚本似乎在长时间的 touchmove 后都会中断。我只在安卓设备上正确测试过,但我尝试了几种不同的浏览器,结果是一样的。我知道e.preventdefault
并且width=device-width
我都在使用,但是这个错误仍然存在。这是我正在使用的代码:
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;
}
}
}
下面是一些示例,您可以在其中测试发生的这种行为:
http://www.onlywebpro.com/demo/gamedev/mouse_detect.html
这些是我在网上找到的不同方法/脚本,到目前为止,我发现的所有 touchmove 代码示例似乎都无法正常工作。如果您在 android 设备上模拟连续拖动,touchmove 将在某个点中断并返回一个 touchend,然后连续返回一个 touchstart,直到您松开手指以停止 touchmove。这可能需要 1 秒或几分钟,但 touchmove 总会在某个时候中断。
任何建议/解决方案将不胜感激。