J. Doe J. Doe - 6 months ago 27
CSS Question

2d grid know if square is in range

I am with javascript and css trying to make a 2d grid which I have made, an 8x8 grid, and I save a number in a variable which is the position on the grid, so 10 would mean square 10 which is the 2nd box on row 2. I am trying to figure out how I can check if a square that I click on, is in 1 square range?

here is a picture of what I mean:

how do I know if I click a green box(1 square away) or not? thank you


You can get the tile coordinates for any given x, y like this:

var tileX = math.floor(x / width_of_tile);
var tileY = math.floor(y / height_of_tile);

You can get the tile coordinates for any given tile index like this:

var tileX = tileIndex % width_of_array
var tileY = math.floor(tileIndex / width_of_array)

You can then compare any of those coordinates, resting sure that any adjacent tile has this condition true:

distX = math.abs(tileXA - tileXB)
distY = math.abs(tileYA - tileYB)
isAdjacent = distX <= 1 && distY <= 1