概要
方法
ComputeRawPathAsync(start: Vector3,finish: Vector3,maxDistance: number):Path |
ComputeSmoothPathAsync(start: Vector3,finish: Vector3,maxDistance: number):Path |
CreatePath(agentParameters: Dictionary):Path |
FindPathAsync(start: Vector3,finish: Vector3):Path |
範例程式碼
使用路徑尋找服務
local PathfindingService = game:GetService("PathfindingService")
local agentParams = {
AgentRadius = 2.0,
AgentHeight = 5.0,
AgentCanJump = false,
}
local currentWaypointIdx = 1
local path = PathfindingService:CreatePath(agentParams)
local humanoidRootPart = script.Parent:FindFirstChild("HumanoidRootPart")
local targetPosition = Vector3.new(50, 0, 50)
path:ComputeAsync(humanoidRootPart.Position, targetPosition)
-- 當路徑被阻擋時...
local function OnPathBlocked(blockedWaypointIdx)
-- 檢查障礙物是否在路徑更前面
if blockedWaypointIdx > currentWaypointIdx then
-- 重新計算路徑
path:ComputeAsync(humanoidRootPart.Position, targetPosition)
if path.Status == Enum.PathStatus.Success then
-- 使用 path:GetWaypoints() 獲取更新的路徑點列表
-- 並繼續朝目標走
else
-- 錯誤,未找到路徑
end
end
end
path.Blocked:Connect(OnPathBlocked)API 參考
屬性
EmptyCutoff
方法
ComputeRawPathAsync
ComputeSmoothPathAsync
CreatePath
參數
| 預設值:"nil" |
返回
範例程式碼
使用導航服務創建路徑
local Workspace = game:GetService("Workspace")
local PathfindingService = game:GetService("PathfindingService")
-- 這個模型包含一個開始、一個結束和三條玩家可以行走的路徑:雪、金屬和樹葉草
local PathOptionsModel = script.Parent.PathOptions
local startPosition = PathOptionsModel.Start.Position
local finishPosition = PathOptionsModel.End.Position
-- 創建一條避免雪和金屬材料的路徑
-- 這將確保創建的路徑避免了雪和金屬路徑並引導
-- 用戶朝樹葉草路徑前進
local path = PathfindingService:CreatePath({
AgentRadius = 3,
AgentHeight = 6,
AgentCanJump = false,
Costs = {
Snow = math.huge,
Metal = math.huge,
},
})
-- 計算路徑
local success, errorMessage = pcall(function()
path:ComputeAsync(startPosition, finishPosition)
end)
-- 確認計算成功
if success and path.Status == Enum.PathStatus.Success then
-- 對於每個途徑點,創建一個部分以可視化路徑
for _, waypoint in path:GetWaypoints() do
local part = Instance.new("Part")
part.Position = waypoint.Position
part.Size = Vector3.new(0.5, 0.5, 0.5)
part.Color = Color3.new(1, 0, 1)
part.Anchored = true
part.CanCollide = false
part.Parent = Workspace
end
else
print(`無法計算路徑,錯誤:{errorMessage}`)
endFindPathAsync