0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jackgba
  • 47
  • 5

1 Answers1

0

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

Current division of space

Nicolas M. Pardo
  • 753
  • 1
  • 6
  • 16
  • The line box.addEventListener('click', chooseSide); it's saying "Cannot read property 'addEventListener' of null". What's wrong? – Jackgba Jul 11 '18 at 20:24
  • Are you loading your script before yout html elements? Also, you need to change the box selector to match your canvas e.g `const box = document.querySelector('.my-canvas');` – Nicolas M. Pardo Jul 11 '18 at 20:27
  • Yep i did it with the window.onload function (just on your script, maybe the problem is that), and I change the canvas but the error continues – Jackgba Jul 11 '18 at 20:45
  • I'll add an edit to show you a canvas and to add it after it is loaded, you can check now, if not, show me your implementation – Nicolas M. Pardo Jul 11 '18 at 20:52
  • Thank you! Now it worked perfectly on mobile, but for some reason the left side click is not working on my PC browser. Any idea? – Jackgba Jul 11 '18 at 21:11
  • If it works you can mark it as the right answer, also you will need to add a couple more validation to get the box size since client width might no be available for all browsers, look up for related answers to get element dimensions js – Nicolas M. Pardo Jul 11 '18 at 21:13