0
\$\begingroup\$

So I have a 7x7 grid made using a for loop and instantiating the sprites. Now via code, let us say l placed my rectangular sprite,which takes 3 cells on the grid, somewhere on that grid. How can I get the position of the cells on which this rectangular sprite is on?

\$\endgroup\$
  • \$\begingroup\$ Show us your for loop. \$\endgroup\$ – DMGregory Aug 10 at 13:35
0
\$\begingroup\$

I will answer for an item that takes 1 cell in the grid. Given the world coordinates (x, y) of the center of this item, you can get the grid coordinates (a, b) by doing the following calculation:

a = ceil((x / cellSize))
b = ceil((y / cellSize))

I'm assuming that the cells are square and that their side is equal to cellSize

Here is a quick example of how you can do it for an item that takes 3 cells in the grid, if it is placed horizontally:

You can calculate the grid coordinates of the left part of your rectangle. You will then know that the cell of coordinates (a, b) is occupied. By consequent, the cells of coordinates (a + 1, b) and (a + 2, b) are occupied too.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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