I have a 2D tile map (made of 25 tiles, each 30*30 pixels) drawn on a JPanel
. How can I get the rectangular coordinates of each tile?
Asked
Active
Viewed 618 times
0

anonymous
- 448
- 1
- 6
- 25
-
I assume a 5x5 grid pattern – MadProgrammer Mar 20 '14 at 03:56
-
yes, I have drawn that, now I want their rectangles. I hope you understand what I am trying to say. – anonymous Mar 20 '14 at 04:03
1 Answers
1
The "basic" approach might be do something like...
int tileWidth = 30;
int tileHeight = 30;
// Coordinates in the physical world, like a mouse point for example...
int x = ...;
int y = ...;
int col = (int)Math.floor(x / (double)tileWidth);
int row = (int)Math.floor(y / (double)tileHeight);
This will return the virtual grid x/y position of each tile based on the physical x/y coordinate
You can then use something like...
int tileX = col * tileWidth;
int tileY = row * tileHeight;
The tile rectangle then becomes tileX
x tileY
x tileWidth
x tileHeight
Now, while this works. A better solution would be to use something like java.awt.Rectangle
and maintain a List
of them, each would represent a individual tile in the real world.
You could then use Rectangle#contains
to determine if a given tile contains the coordinates you are looking for.
The other benefit of this, is Rectangle
is printable using Graphics2D#draw
and/or Graphics2D#fill

MadProgrammer
- 343,457
- 22
- 230
- 366