NPC pathfinding glitches when player is across a gap


How do I get the script to recognize when the player is across a gap?

script:

local pathfinding = game:GetService(“PathfindingService”)
local players = game:GetService(“Players”)
local runService = game:GetService(“RunService”)

local path = pathfinding:CreatePath({
agentHeight = 1;
agentRadius = 1;
agentCanJump = false;

Costs = {
	Water = 100;
	DangerZone = math.huge
}

})

local char = script.Parent
local hum = char:WaitForChild(“Humanoid”)

local waypoints
local nextWayPointIndex
local reachedConnection
local blockedConnection

local function findTarget()
local maxDistance = 500
local nearestTarget

for index, player in pairs(players:GetPlayers()) do
	if player.Character then
		local target = player.Character
		local distance = (char.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
		
		if distance < maxDistance then
			nearestTarget = target
			maxDistance = distance
		end
		
		if distance < 4 then
			nearestTarget.Humanoid:TakeDamage(1)
		end
	end
end

return nearestTarget

end

local function wander()

local waypoints = game.Workspace:WaitForChild("Waypoints")
local newWaypoint = Instance.new("Part")

local randomPos randomPos = math.random(1, 10)

newWaypoint.Position = char.PrimaryPart.Position + Vector3.new(randomPos, 0, randomPos)

end

local function followPath(destination)
local success, errorMessage = pcall(function()
path:ComputeAsync(char.PrimaryPart.Position, destination)
end)

if success and path.Status == Enum.PathStatus.Success then
	waypoints = path:GetWaypoints()
	
	blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
		
		if blockedWaypointIndex >= nextWayPointIndex then
			blockedConnection:Disconnect()
			followPath(destination)
		end
		
	end)
	
	if not reachedConnection then
		reachedConnection = hum.MoveToFinished:Connect(function(reached)
			if reached and nextWayPointIndex < #waypoints then
				nextWayPointIndex += 1
				hum:MoveTo(waypoints[nextWayPointIndex].Position)
			else
				reachedConnection:Disconnect()
				blockedConnection:Disconnect()
			end
		end)
	end
	
	nextWayPointIndex = 2
	hum:MoveTo(waypoints[nextWayPointIndex].Position)
else
	warn("path not computed", errorMessage)
end

end

while wait() do
local target = findTarget()
if target then
followPath(target.HumanoidRootPart.Position)
end
end

My apologies, I dont know how to paste code correctly

1 Like