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]
}
}
}
}
You can do this mathematically and derive the grid cell directly from
tPoswithout having to search the squares!There are a few assumptions here:
Caveat: I haven't actually tested this code!