J. Doe - 1 year ago 82

CSS Question

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:

image

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**