I'm studying js and making a Tetris game. I already made it in PC dispositives but I want to add some touch events to the game works on mobile dispositives. But I'm stuck at this:
function touchEnd(e) {
if (Math.abs(offset[0]) > Math.abs(offset[1])) {
playerMove(-1);
}
else if (Math.abs(offset[0]) < Math.abs(offset[1])) {
playerDrop();
}
}
(I'm having trouble with this code above)
My idea is when the player touches (not dragging) at the left of the screen (canvas), the playerMove(-1)
works, when you touch at the right, the playerMove(1);
works, and when you touch at the bottom of the screen, the playerDrop()
works. How can I do this? Thank you.
This is an example on how you can split an HTMLElement and send actions based on that
let box;
document.addEventListener('DOMContentLoaded', ()=>{
box = document.querySelector('#test');
box.addEventListener('click', chooseSide);
});
function chooseSide(e){
const {clientX, clientY} = e;
const {clientHeight, clientWidth} = box
if(clientY > (clientHeight/ 2)){
console.log('bottom')
}else if(clientX < (clientWidth/ 2)){
console.log('left')
} else{
console.log('right')
}
}
#test {
box-sizing: border-box;
width: 100vmin;
height: 100vmin;
border: 10px solid #f00;
}
<canvas id="test"></canvas>
You can change the value of the Y comparison, and give more or less space to what the "bottom" is