1

(this image is not mine, but it helps ilustrate the point)

enter image description here

Give this grid with each tile beign 32x32 pixels, how can i calculate the tile ID where the mouse is?

In this case, mouse is on tile: 40.

3
  • What integers are given? What is height and width?
    – square1001
    Dec 12, 2016 at 5:18
  • 3
    Is the position mentioned for green tile?Because if it is then should it not be 44 instead of 39? Dec 12, 2016 at 5:35
  • Yes. Thanks for pointing that out.
    – Jh62
    Dec 12, 2016 at 11:38

1 Answer 1

2

Let us say the current mouse position is (x,y) and the length of each small square is l(in the given case 32). Then, the grid x and y value will be given by:

gridX = x/l; //be sure it is integer division and not float
gridY = y/l; //

Then calculate the tile id on the basis of those values:

currentTileId = (boxesEachRow * gridY) + gridX + 1;

where boxesEachRow is the number of boxes along each row(here it is 8). The plus 1 is needed if you are treating the first box's id as 1 and not 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.