im trying to make a ai that can roam. but just dont know how to. with out breaking the go after player
so bascily if the player is near and not behind a wall. it goes after player. other then that it does a roam.
but i tried to before and it jusr broke. so i made a go after player only script. plz help:
-- Variables --
local Pathfinding = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local path = Pathfinding:CreatePath({
AgentHeight = 6;
AgentRadius = 3;
AgentCanJump = false;
Costs = {
Water = 100;
DangerZone = math.huge
}
})
local Character = script.Parent
local humanoid = Character: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 = (Character.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance then
nearestTarget = target
maxDistance = distance
end
if distance < 5 then
nearestTarget.Humanoid:TakeDamage(25)
end
end
end
return nearestTarget
end
local function followPath(destination)
local success, errorMessage = pcall (function()
path:ComputeAsync(Character.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 = humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointIndex < #waypoints then
nextWaypointIndex += 1
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
reachedConnection:Disconnect()
blockedConnection:Disconnect()
end
end)
end
nextWaypointIndex = 2
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
warn("Path not computed!", errorMessage)
end
end
while wait() do
local target = findTarget()
if target then
print(target.Name)
followPath(target.HumanoidRootPart.Position)
end
end
roam points: script.Parent.Parent.AiPaths:GetChildren()