GameApi.getUnitsInArea(tileRange)
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/1209
GameApi.getUnitsInArea()
的型別宣告與其他查詢方法一同出現在 @chronodivide/game-api
的介面中:
getAllUnits(filter?: (r: TechnoRules) => boolean): number[];
/** Queries neutral units and buildings on the map */
getNeutralUnits(filter?: (r: TechnoRules) => boolean): number[];
/** Queries units in a given area of tiles. Uses a quadtree and is more efficient than scanning tile by tile. */
getUnitsInArea(tileRange: Box2): number[];
其中 tileRange
的型別 Box2
是 THREE.Box2
的延伸,用於表示矩形區域的最小與最大座標:
export declare class Box2 extends THREE.Box2 {
}
壓縮後的實作顯示,方法會透過地圖的 quadtree (technosByTile
) 查詢範圍內的物件,並回傳它們的 ID:
getUnitsInArea(e){return Mp(this,Lp,"f").map.technosByTile.queryRange(e).map(e=>e.id)}
方法說明
-
輸入:
tileRange
為Box2
,用 tile 坐標表示查詢範圍。 -
輸出:回傳範圍內所有單位/建築的 ID 陣列。
-
特色:利用 quadtree 資料結構,可在大片地圖上快速取得指定區域的單位,而不必逐格遍歷。
使用範例
以下示例在遊戲開始時,檢查 (50,50) 周圍 10×10 的區域內有哪些物件,並列出它們的名稱與位置。
import { cdapi, Bot, GameApi, Box2, Vector2 } from "@chronodivide/game-api";
class AreaScannerBot extends Bot {
onGameStart(game: GameApi) {
// 以 (50,50) 為中心,半徑 5 格
const area = new Box2(
new Vector2(45, 45),
new Vector2(55, 55),
);
const unitIds = game.getUnitsInArea(area);
console.log(`Units in area: ${unitIds.length}`);
unitIds.forEach((id) => {
const data = game.getGameObjectData(id);
if (data) {
console.log(`${data.name} at (${data.tile.rx}, ${data.tile.ry})`);
}
});
}
}
async function main() {
await cdapi.init(process.env.MIX_DIR!);
await cdapi.createGame({
agents: [new AreaScannerBot("Scanner", "Americans")],
mapName: "mp03t4.map",
shortGame: true,
online: false,
});
}
main().catch(console.error);
在 onGameStart
中建立 Box2
以定義查詢範圍,再使用 getUnitsInArea
取得其中的單位 ID 並進一步查詢資料。
由於此方法利用 quadtree 快速檢索,特別適合在需要偵測區域內單位時(如搜索附近敵軍、判斷建築空位等)使用。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at