htmlmobiletouchgame-development

I'm not sure why my site on mobile isn't working properly, can you please advise?


I've developed an html snake game, but I want to make it on mobile. This works fine on desktop, but when I want to go onto my mobile and play, the controls are bugging out, stopping the game, restarting, it's essentially unplayable, and I have no idea what is happening. I've tried using these touch controls below.

// touch controls
document.addEventListener('touchstart', function (e) {
  const touchX = e.touches[0].clientX;
  const touchY = e.touches[0].clientY;

  const halfWidth = window.innerWidth / 2;
  const halfHeight = window.innerHeight / 2;

  if (touchX < halfWidth) {
    if (!gameStarted) {
      // Start the game if touched on the left side and the game is not already started
      startGame();
    } else {
      // Tapped on the left side
      if (snake.dx === 0) {
        // Change direction to the left only if not already moving horizontally
        snake.dx = -grid;
        snake.dy = 0;
      }
    }
  } else {
    // Tapped on the right side
    if (snake.dx === 0) {
      // Change direction to the right only if not already moving horizontally
      snake.dx = grid;
      snake.dy = 0;
    }
  }

  if (touchY < halfHeight && !gameStarted) {
    // Start the game if touched on the top side and the game is not already started
    startGame();
  } else if (touchY >= halfHeight) {
    // Tapped on the bottom side
    if (snake.dy === 0) {
      // Change direction downward only if not already moving vertically
      snake.dy = grid;
      snake.dx = 0;
    } else if (touchY < halfHeight) {
    // Tapped on the bottom side
    if (snake.dy === 0) {
      // Change direction upward only if not already moving vertically
      snake.dy = -grid;
      snake.dx = 0;
    }
  }
});

Solution

  • Using touchend should mitigate unintentional interactions that users makes with the touchscreen. Depending on your program requirements, you might need to use a combination of touchstart and touchend to best handle all the touch interactions.

    document.addEventListener('touchend', function (e) {
    

    Also try using e.changedTouches instead.

    const touchX = e.changedTouches[0].clientX;
    const touchY = e.changedTouches[0].clientY;