getting rectangular coordinates of tiles of a 2D map

不羁的心 提交于 2021-01-29 17:41:00

问题


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?


回答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



来源:https://stackoverflow.com/questions/22523167/getting-rectangular-coordinates-of-tiles-of-a-2d-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!