calculate the direction of touch (top || right || bottom || left)

Asked

Viewed 37 times

1

To move the tail in this game https://leonardovita.github.io/javascript-snake-game/ using the touch screen of the mobile phone, need to calculate the position of the click on the screen, as in the example of the image below, only one direction can be received

or any other native javascript solution more efficient than to move the cover with touch

  const screenWidth = window.screen.width;
  const screenHeight = window.screen.height;

  document.addEventListener("click",handleClickTouchPad)
  function handleClickTouchPad(event){

    //calcula o X e o Y para determinar qual triangulo da imagem abaixo foi o click

    if(up === true ){

      //move para cima   
    }
    else if ( right === true){
        //move para direita
    }else 
    ...
  }

inserir a descrição da imagem aqui

1 answer

1

I guess now that code solves:

    //elemento em que ocorrerá o touch swipe
    let area = document.querySelector("#area");
    let centerPosition = {
        x:area.clientWidth/2,
        y:area.clientHeight/2
    };
    area.onclick = (event) => {
        let clickPosition = {
            x:event.offsetX,
            y:event.offsetY
        }
        
        let x = clickPosition.x - centerPosition.x;
        let y = clickPosition.y - centerPosition.y;

        if(Math.abs(x) > Math.abs(y)){
            if(x > 0){
                console.log("right");
            }else{
                console.log("left");
            }
        }else{
            if(y > 0){
                console.log("bottom");
            }else{
                console.log("top");
            }
        }
    };
  • Interesting guy your solution, pretty cool to work with the touch so, but the game of the cover needs more speed if not the player loses, play dragging your finger and very slow, the right same would only be in the touches

  • Valew man, I tried to adjust according to what you reported to me, so I edited my solution and I think now can help you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.