TiledLayer 將單一大圖分割為等大小的小圖塊,透過二維陣列索引組合成遊戲地圖,適用於 RPG、SLG 等大場景遊戲。
public TiledLayer(int columns, int rows, Image image, int tileWidth, int tileHeight)
columns/rows:地圖橫向/縱向格子數image:包含所有圖塊的大圖(橫向排列)tileWidth/tileHeight:單一圖塊寬高,自動分割大圖Image tileset = Image.createImage("/tiles.png"); // 含 9x9 種圖塊
TiledLayer map = new TiledLayer(20, 15, tileset, 16, 16); // 20x15 格地圖,每格 16x16
// 在 (col, row) 位置貼上索引為 tileIndex 的圖塊
map.setCell(col, row, tileIndex);
索引規則:0 為空白,1 起始對應大圖左上角第一塊,依序遞增。
// 地圖資料:9x9 範例
final static int[][] mapData = {
{4,4,4,4,4,4,4,4,4},
{4,1,2,3,1,3,2,1,4},
{4,1,5,1,1,2,4,3,4},
{4,3,5,6,4,3,7,8,4},
{4,3,6,7,7,7,3,2,4},
{4,7,2,1,1,1,6,2,4},
{4,3,6,7,7,7,3,2,4},
{4,7,2,1,1,1,6,2,4},
{4,4,4,4,4,4,4,4,4}
};
// 雙層迴圈貼磚
for (int y = 0; y < mapData.length; y++) {
for (int x = 0; x < mapData[y].length; x++) {
map.setCell(x, y, mapData[y][x]);
}
}
// 繪製整張地圖
map.paint(g);
// 僅繪製可視區域(配合攝影機座標)
map.paint(g, cameraX, cameraY, screenWidth, screenHeight);
flushGraphics(x,y,w,h) 局部更新setCell 索引