所以我的游戏很像马里奥,但在JS画布和它的PC和移动的兼容.我已经得到了左和右触摸运动的工作,但现在我只是试图使跳跃事件以及。我试着做:addEventListener('touchmove', e => { player.velocity.y -= 15 })但它不会工作,因为我试图使它只触发时,我向上滑动。
addEventListener('touchmove', e => { player.velocity.y -= 15 })
jtoj6r0c1#
要检测滑动手势,您可以监听touchstart和touchmove事件,并分别存储开始和最后的位置。然后在touchend事件上比较两个位置以查看用户是否向上移动(也存在用户没有移动的可能性)
const MIN_DISTANCE = 50; const canvas = document.querySelector("#canvas"); const ctx = canvas.getContext('2d'); let startPosition; let lastPosition; const onDown = event => { startPosition = getTouchPosition(event); lastPosition = null; }; const onMove = event => { lastPosition = getTouchPosition(event); }; const onUp = event => { // didn't move if (! lastPosition) { return showMessage("DIDN'T MOVE"); } var yDiff = Math.abs(startPosition.y - lastPosition.y); // didn't move enough to be considered a swipe if (yDiff < MIN_DISTANCE) { return showMessage('NOT A SWIPE'); } if (startPosition.y > lastPosition.y) { showMessage('SWIPE UP') } else { showMessage('SWIPE DOWN'); } }; // Touch canvas.addEventListener('touchstart', onDown); canvas.addEventListener('touchend', onUp); canvas.addEventListener('touchmove', onMove); // Mouse canvas.addEventListener('mousedown', onDown); canvas.addEventListener('mousemove', onMove) canvas.addEventListener('mouseup', onUp); function showMessage(text) { canvas.width = canvas.width; ctx.font = '20px bold Arial'; ctx.fillText(text, 100, 100); } function getTouchPosition(event) { if (! event.touches) { return { x: event.clientX, y: event.clientY } } return { x: event.touches[0].clientX, y: event.touches[0].clientY }; }
canvas { border: 1px solid black; }
<canvas id="canvas" width="400" height="500"></canvas>
1条答案
按热度按时间jtoj6r0c1#
要检测滑动手势,您可以监听touchstart和touchmove事件,并分别存储开始和最后的位置。
然后在touchend事件上比较两个位置以查看用户是否向上移动(也存在用户没有移动的可能性)