简体   繁体   中英

touchmove handler after touchstart handler wont work

I have a problem with an touchmove event. When the user touches the display (touchstart) the touchmove event handler and game() should be executed and if the user leaves the screen everything should be stopped. But then the if conditions for the collisiondetection interval won't work right because e.pageX and e.pageY always have the coordinates of the touchstart and won't update their values when the user moves their finger (touchmove) on the screen. How can I fix this? demo

$("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);
    }
});

UPDATE: If I edit it to 'touchstart mousedown touchmove mousemove': function (e) { the collision detection and the updating coordinates works well but the animation dont.

Becasue your code doesn't update the coordinates when users move their fingers.

$("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);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM