Engine Class
PathfindingService
*เนื้อหานี้แปลโดยใช้ AI (เวอร์ชัน Beta) และอาจมีข้อผิดพลาด หากต้องการดูหน้านี้เป็นภาษาอังกฤษ ให้คลิกที่นี่
สรุป
คุณสมบัติ
วิธีการ
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" |
ส่งค่ากลับ
ตัวอย่างโค้ด
การสร้างเส้นทางด้วยบริการ Pathfinding
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