Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top