I’ve got a pathfinding AI for my enemy, however it does not go up slopes. On my stairs, I have each step’s CanCollide off, and instead having an invisible wedge for collisions. When I go up the stairs, the AI is not able to follow me, and gives an error in the console.
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local path = PathfindingService:CreatePath({
AgentRadius = 3,
AgentHeight = 6,
AgentCanJump = true,
Costs = {
Water = 20
}
})
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
local function followPath(destination)
-- Compute the path
local success, errorMessage = pcall(function()
path:ComputeAsync(character.PrimaryPart.Position, destination)
end)
if success and path.Status == Enum.PathStatus.Success then
-- Get the path waypoints
waypoints = path:GetWaypoints()
-- Detect if path becomes blocked
blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
-- Check if the obstacle is further down the path
if blockedWaypointIndex >= nextWaypointIndex then
-- Stop detecting path blockage until path is re-computed
blockedConnection:Disconnect()
-- Call function to re-compute new path
followPath(destination)
end
end)
-- Detect when movement to next waypoint is complete
if not reachedConnection then
reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointIndex < #waypoints then
-- Increase waypoint index and move to next waypoint
nextWaypointIndex += 1
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
reachedConnection:Disconnect()
blockedConnection:Disconnect()
end
end)
end
-- Initially move to second waypoint (first waypoint is path start; skip it)
nextWaypointIndex = 2
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
warn("Path not computed!", errorMessage)
end
end
while task.wait() do
local players = game.Players:GetPlayers()
local MaxDistance = 1000
local nearestTarget
for i,v in pairs(players) do
if (v.Character) then
local target = v.Character
local distance = (script.Parent.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if (distance < MaxDistance) then
nearestTarget = target
MaxDistance = distance
end
end
end
if nearestTarget ~= nil then
followPath(nearestTarget.HumanoidRootPart.Position)
end
end