MapApi.getObjectsOnTile(tile)
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1228
MapApi.getObjectsOnTile(tile)
會回傳指定格子上所有物件的 ID 陣列。
在套件的型別宣告中,可看到這個方法位於 MapApi
介面中:
getTilesInRect(rectangle: Rectangle): Tile[];
getTilesInRect(baseTile: Tile, size: Size): Tile[];
getObjectsOnTile(tile: Tile): number[];
hasBridgeOnTile(tile: Tile): boolean;
壓縮後的實作分成兩層:
最底層從 tileOccupation
取得儲存在該格子的物件集合:
getObjectsOnTile(e) {
return [...this.tileOccupation[e.rx]?.[e.ry] ?? []]
}
而 MapApi
對外公開的函式則把這些物件轉成 ID 陣列:
getObjectsOnTile(e) {
return Op(this, Cp, "f").getObjectsOnTile(e).map(e => e.id)
}
使用範例
以下 Bot 於遊戲開始時取得 (50,50) 的 Tile,列出該格子所有可見物件的名稱與類型:
import { cdapi, Bot, GameApi } from "@chronodivide/game-api";
class TileInspectorBot extends Bot {
onGameStart(game: GameApi) {
const tile = game.mapApi.getTile(50, 50);
if (!tile) {
console.log("Tile (50,50) 不在地圖內");
return;
}
const ids = game.mapApi.getObjectsOnTile(tile);
console.log(`Objects on (${tile.rx},${tile.ry}):`, ids.length);
ids.forEach(id => {
const data = game.getGameObjectData(id);
if (data) {
console.log(`- ${data.name} [${data.type}]`);
}
});
}
}
async function main() {
await cdapi.init(process.env.MIX_DIR!);
await cdapi.createGame({
agents: [new TileInspectorBot("Viewer", "Americans")],
mapName: "mp03t4.map",
shortGame: true,
online: false,
});
}
main().catch(console.error);
getObjectsOnTile
提供快速查詢功能,可判斷某格是否已有單位或建築佔據,亦能用來搜尋特定地形物件(如礦脈、橋樑等)。
由於底層直接存取 tileOccupation
的資料結構,效率比逐格掃描高,在路徑規劃或建築放置邏輯中十分實用。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at