Lớp công cụ
PathfindingService
*Nội dung này được dịch bằng AI (Beta) và có thể có lỗi. Để xem trang này bằng tiếng Anh, hãy nhấp vào đây.
Tóm Tắt
Thuộc Tính
Phương Pháp
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 |
Mẫu mã
Sử dụng Dịch vụ Tìm đường
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)
-- Khi con đường bị chặn...
local function OnPathBlocked(blockedWaypointIdx)
-- Kiểm tra xem chướng ngại vật có ở xa hơn trên con đường không
if blockedWaypointIdx > currentWaypointIdx then
-- Tính lại con đường
path:ComputeAsync(humanoidRootPart.Position, targetPosition)
if path.Status == Enum.PathStatus.Success then
-- Lấy danh sách waypoint được cập nhật với path:GetWaypoints()
-- và Tiếp tục đi về phía mục tiêu
else
-- Lỗi, không tìm thấy đường
end
end
end
path.Blocked:Connect(OnPathBlocked)Tài Liệu Tham Khảo API
Thuộc Tính
EmptyCutoff
Phương Pháp
ComputeRawPathAsync
ComputeSmoothPathAsync
CreatePath
Tham Số
| Giá Trị Mặc Định: "nil" |
Lợi Nhuận
Mẫu mã
Tạo Đường Dẫn với Dịch Vụ Tìm Đường
local Workspace = game:GetService("Workspace")
local PathfindingService = game:GetService("PathfindingService")
-- Mô hình này chứa một điểm bắt đầu, một điểm kết thúc và ba đường dẫn mà người chơi có thể đi: Tuyết, Kim Loại và Cỏ Rậm
local PathOptionsModel = script.Parent.PathOptions
local startPosition = PathOptionsModel.Start.Position
local finishPosition = PathOptionsModel.End.Position
-- Tạo một đường dẫn tránh các vật liệu Tuyết và Kim Loại
-- Điều này sẽ đảm bảo rằng đường dẫn được tạo ra tránh các đường dẫn Tuyết và Kim Loại và hướng
-- người dùng tới đường dẫn Cỏ Rậm
local path = PathfindingService:CreatePath({
AgentRadius = 3,
AgentHeight = 6,
AgentCanJump = false,
Costs = {
Snow = math.huge,
Metal = math.huge,
},
})
-- Tính toán đường dẫn
local success, errorMessage = pcall(function()
path:ComputeAsync(startPosition, finishPosition)
end)
-- Xác nhận việc tính toán thành công
if success and path.Status == Enum.PathStatus.Success then
-- Đối với mỗi điểm dừng, tạo một phần để trực quan hóa đường dẫn
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(`Không thể tính toán đường dẫn, lỗi: {errorMessage}`)
endFindPathAsync