路径 对象存储由 PathfindingService:CreatePath() 创建的路径的结果。
一旦创建了路径对象,您可以使用起始点和终点调用 Path:ComputeAsync()。这将尝试计算角色沿着的有效路径,基于默认或自定义参数传递到 CreatePath() 。如果 ComputeAsync() 成功找到路径,那么 Path 对象将有一个 Path.Status 值的 Enum.PathStatus.Success 。否则状态将为 Enum.PathStatus.NoPath ,这可能发生在两个点之间有障碍物(且没有办法绕过)或者点位于固体物体内。
除了 ComputeAsync() 之外,Path 对象还有 GetWaypoints() 方法,该方法返回一个列表代表角色应按顺序从开始到路径终点的路径的点的路径点。
最后,Path可以 连接 到Path.Blocked。此事件将在路径存在期间的任何时间发生,如果路径被阻塞。请注意,这可能会在 个字符沿路移动后 发生,而不仅仅在它前面。
属性
方法
GetWaypoints
这个函数返回一个阵列,包含所有 PathWaypoints 在一个 Path 中,由 Path:ComputeAsync() 计算。
阵列中的每个路径点都指定一个 Vector3 位置和 action 当这个路径点达到时需要采取的位置。阵列按路径从起点到结束点的顺序排列。
如果无法计算路径,该函数将返回一个空数组。
返回
从路径开始到路径结束的一系列 PathWaypoints 数组。
代码示例
The example below demonstrates how to create a Path and it's PathWaypoints using the PathService.
It tries to Path:ComputeAsync() a path between two Vector3 positions, from pathStart to pathEnd. If a path is successfully created, indicated by it's Enum.PathStatus, the code block gets an array of its waypoints using Path:GetWaypoints(). Then, it loops through the array and prints each waypoint's position.
local PathfindingService = game:GetService("PathfindingService")
local path = PathfindingService:CreatePath()
local PATH_START = Vector3.new(0, 1, 0)
local PATH_END = Vector3.new(100, 1, 25)
path:ComputeAsync(PATH_START, PATH_END)
if path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
for _, waypoint in pairs(waypoints) do
print(waypoint.Position)
end
end
CheckOcclusionAsync
这个函数检查路径是否从指示的路径点开始被阻塞。 start 指示的路径点是路径的起点。
如果被阻止,返回遮蔽的第一个路径点;如果没有,返回 -1。如果 开始 小于 0 或大于 Path 中的路径点数,将返回错误。
参数
返回
ComputeAsync
这个函数计算从起始位置到终止位置的 Path 。当路径创建时,此函数不会自动调用,必须每次路径需要更新时才能调用。
一旦路径计算出来,它将有一系列路径点,当跟随时,可以将角色引导在路径上。这些点由 Path:GetWaypoints() 函数收集。
参数
返回
代码示例
The code sample below explores how to move an NPC along a more complex path or around obstacles. This is known as pathfinding.
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)
-- When the path is blocked...
local function OnPathBlocked(blockedWaypointIdx)
-- Check if the obstacle is further down the path
if blockedWaypointIdx > currentWaypointIdx then
-- Recompute the path
path:ComputeAsync(humanoidRootPart.Position, targetPosition)
if path.Status == Enum.PathStatus.Success then
-- Retrieve update waypoint list with path:GetWaypoints()
-- and Continue walking towards target
else
-- Error, path not found
end
end
end
path.Blocked:Connect(OnPathBlocked)