首页 文章

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

提问于
浏览
3

我正在开发一款名为“ grab 掉落物体”的简单游戏 . 在桌面设备上,游戏运行良好且流畅 . 当您按下左右键时,“太空火箭”(使用以下链接查看游戏)在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");
});

有谁能建议更好的解决方案?这是游戏Game的链接,这里是我的游戏的完整代码code

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

更新2:我改变了我在屏幕上检测印刷机的方式

1 回答

  • 0

    在@ 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;
        }
    });
    

相关问题