如何在移动设备上使画布上的对象在 x 轴上平滑地左右移动



我正在做一个简单的游戏,叫做"接住坠落的物体"。在桌面设备上,游戏运行良好且流畅。当您左右按键时,"太空火箭"(使用以下链接查看游戏)在 x 轴上平滑移动。现在在移动设备上,我遇到了一个小问题。当你按下左侧或右侧时,"太空火箭"正在正常移动。但是,当您按住"火箭"时,它不会沿着您在屏幕上不断按下的方向移动。如果你松开你的手,你会看到火箭从一个位置"跳"到另一个位置,并且不像在桌面上那样流畅地移动。我执行了以下代码,但无法正常工作

更新 2

var mc = new Hammer(htmlCanvas);
mc.add(new Hammer.Press({ event: 'press', time:1 }));
mc.on("press", function(ev) {
    console.log("dsaDS");
    touchDown = true;
setInterval(function(){
   while(touchDown) { 
        console.log("down");
            if (ev.center.x < player.x)
            {
                player.x -=  Math.floor(CANVAS_WIDTH / player.width);
            }
            else
            {
                player.x += Math.floor(CANVAS_WIDTH / player.width);
            }
            if (ev.center.x == player.x)
            {
                touchDown = false;
            }
    } }, 1000);
});
mc.on("pressup", function(ev) {
    touchDown = false;
    console.log("up");
});

谁能提出更好的解决方案?这是游戏的链接游戏,这是我的游戏代码的完整代码

更新1:它不适用于任何设备,iOS和Android

更新2:我改变了检测屏幕上新闻的方式

在@Me.Name 和@Blindman67的帮助下,我提出了以下解决方案:

function move(touchDown)
{
     if(touchDown)
     {
       touchMoves =  setTimeout(function(){
            if (Math.floor(touchX) < Math.floor(player.x + player.width))
            {
                if ((Math.floor(player.x + player.width) - Math.floor(touchX)) <= 10 )
                {
                    touchDown = false;
                    clearTimeout(touchMoves);
                }
                else
                {
                   player.x -=  Math.floor(CANVAS_WIDTH / player.width); 
                }
            }
            else if ((Math.floor(touchX) == Math.floor(player.x + player.width)) || (player.x == (CANVAS_WIDTH - player.width)))
            {
                touchDown = false;
                clearTimeout(touchMoves);
            }
            else
            {
                if ((Math.floor(touchX) - Math.floor(player.x + player.width)) <= 10 )
                {
                    touchDown = false;
                    clearTimeout(touchMoves);
                }
                else
                {
                   player.x +=  Math.floor(CANVAS_WIDTH / player.width); 
                }
            }
            if (touchDown)
            {
                move(touchDown);  
            }
        }, 100);
     }
}
mc.on("press", function(ev) {
    if (gameIsActive)
    {
        touchDown = true;
        touchX = ev.center.x;
        move(touchDown);
   }
});
mc.on("pressup", function(ev) {
    if (gameIsActive)
    {
        touchDown = false;
    }
});

最新更新