Js touch position is not accurate

79 Views Asked by At

I am making a chess game in JavaScript using Canvas 2D Rendering Context.

The problem I got is that my input code is not working accurately. I add 40 to the square position because it is the width and the height of the square

The problem in my code is when touch the square nearby squares are getting clicked on rather than what I wanted to click.

Can you help me with a better solution?

function touchCoordToSquare(squares,tPos){
  for (var i = 0; i < squares.length; i++) {
    if(tPos.x > squares[i].pos.x && tPos.x < squares[i].pos.x + 40){
      if(tPos.y > squares[i].pos.y && tPos.y < squares[i].pos.y + 40){
        return squares[i]
      }
    }
  }
}
1

There are 1 best solutions below

0
phuzi On

You can do this mathematically and derive the grid cell directly from tPos without having to search the squares!

There are a few assumptions here:

  • the chessboard squares are 40×40px
  • all co-ordinates start at top-left
  • there are 64 squares in a single flattened array and indexed like this
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
...
56 57 58 59 60 61 62 63

function touchCoordToSquare(squares,tPos){
  const cellSize = 40;
  
  const row = Math.floor(tPos.y / cellSize);
  const column = Math.floor(tPos.x / cellSize);
  
  const squareIndex = row * 8 + column;
  
  return squares[squareIndex];
}

Caveat: I haven't actually tested this code!