Hello I just started learning pathfinding and using bots, i’ve watched some tutorials and ended up with this script, so far it works however theres issues when the npc tries to jump on/off something it just keeps jumping and jumping.
local pathFinding = game:GetService('PathfindingService')
local plr = game:GetService('Players')
local runService = game:GetService('RunService')
script.Parent.PrimaryPart:SetNetworkOwner(nil)
local path = pathFinding:CreatePath({
AgentHeight = 2;
AgentRadius = 2;
AgentCanJump = true;
Costs = {
Water = 100;
CrackedLava = 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 = 40
local nearestTarget
for _, player in (plr:GetPlayers()) do
if player.Character then
local target = player.Character
local distance = (char.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance and target:FindFirstChild('Humanoid').Health > 0 then
nearestTarget = target
maxDistance = distance
end
if distance < 5 and target:FindFirstChild('Humanoid').Health > 0 then
nearestTarget.Humanoid:TakeDamage(25)
end
if distance < 40 then
-- hum:MoveTo((char.HumanoidRootPart.CFrame*CFrame.new(0,0, -10)).Position)
end
end
end
return nearestTarget
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
for _, waypoint in (waypoints) do
local part = Instance.new('Part')
part.Shape = 'Ball'
part.Material = 'Neon'
part.Size = Vector3.new(0.5,0.5,0.5)
part.Position = waypoint.Position
part.Anchored = true
part.CanCollide = false
part.Parent = game.Workspace
game:GetService('Debris'):AddItem(part,0.1)
-- change humanoid state to jump if necessary
if waypoint.Action == Enum.PathWaypointAction.Jump then
hum:ChangeState(Enum.HumanoidStateType.Jumping)
end
end
nextWaypointIndex = 2
hum:MoveTo(waypoints[nextWaypointIndex].Position)
else
warn('Path not computed!', errorMessage)
end
end
while task.wait() do
local target = findTarget()
if target then
followPath(target.PrimaryPart.Position)
else
followPath(workspace:FindFirstChild('Bots').BotBed.Position)
end
end