2016-04-05 138 views
2

我遇到touchmove事件的问题。当用户触摸显示器(touchstart)时,应该执行touchmove事件处理程序和game(),并且如果用户离开屏幕,则应该停止一切。但是,如果collisiondetection间隔的条件不适用,因为e.pageXe.pageY始终具有touchstart的坐标,并且在用户在屏幕上移动其手指(touchmove)时不会更新其值。我怎样才能解决这个问题? demotouchstart处理程序不会工作后touchmove处理程序不会工作

$("body").on({ 
    'touchstart mousedown': function (e) { 
     $(this).on('touchmove mousemove'); 

     collisiondetection = setInterval(function() { 
      var xp1 = $("#n1").position(); 
      if (e.pageY >= xp1.top && e.pageY <= xp1.top + cy * 10 && e.pageX >= xp1.left && e.pageX <= xp1.left + cx * 25) { 
       console.log("hit"); 
      } 
      var xp2 = $("#n2").position(); 
      if (e.pageY >= xp2.top && e.pageY <= xp2.top + cy * 10 && e.pageX >= xp2.left && e.pageX <= xp2.left + cx * 25) { 
       console.log("hit"); 
      } 
     },10); 

     game(); 
    }, 
    'touchend mouseup': function (e) { 
     $(this).off('touchmove mousemove'); 
    clearInterval(animaterects); 
    clearInterval(collisiondetection); 
    } 
}); 

更新:如果我是编辑,以'touchstart mousedown touchmove mousemove': function (e) {碰撞检测和更新坐标作品很好,但动画不。

回答

1

由于用户移动手指时,代码不会更新坐标。

$("body").on({ 
    'touchstart mousedown': function (e) { 
     var pageX = e.pageX 
     var pageY = e.pageY; 
     $(this).on('touchmove mousemove',function(e){ 
      pageX = e.pageX; 
      pageY = e.pageY; 
     }); 

     collisiondetection = setInterval(function() { 
      var xp1 = $("#n1").position(); 
      if (pageY >= xp1.top && pageY <= xp1.top + cy * 10 && pageX >= xp1.left && pageX <= xp1.left + cx * 25) { 
       console.log("hit"); 
      } 
      var xp2 = $("#n2").position(); 
      if (pageY >= xp2.top && pageY <= xp2.top + cy * 10 && pageX >= xp2.left && pageX <= xp2.left + cx * 25) { 
       console.log("hit"); 
      } 
     },10); 

     game(); 
    }, 
    'touchend mouseup': function (e) { 
     $(this).off('touchmove mousemove'); 
    clearInterval(animaterects); 
    clearInterval(collisiondetection); 
    } 
});