[英]getting rectangular coordinates of tiles of a 2D map
我在JPanel
上繪制了一個2D瓦片地圖(由25個瓦片組成,每個30 * 30像素)。 如何獲得每個圖塊的直角坐標?
“基本”方法可能類似於...
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);
這將基於物理x / y坐標返回每個圖塊的虛擬網格x / y位置
然后,您可以使用類似...
int tileX = col * tileWidth;
int tileY = row * tileHeight;
然后,該矩形圖塊將變為tileX
x tileY
x tileWidth
x tileHeight
現在,盡管這可行。 更好的解決方案是使用java.awt.Rectangle
東西並維護它們的List
,每個都代表現實世界中的單個圖塊。
然后,您可以使用Rectangle#contains
確定給定的圖塊是否包含您要查找的坐標。
這樣做的另一個好處是,可以使用Graphics2D#draw
和/或Graphics2D#fill
打印Rectangle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.