Hello, so, i have been creating a horror game and this is the AI for the enemy, i want to make it work like how the title says (if the player is close the dummy follows him, else if its far it just go the waypoints)
if anyone can help me i would appreciate it
Anyways, here is the full code:
local pathfindingService = game:GetService('PathfindingService')
local runService = game:GetService('RunService')
local gameFolder = workspace:FindFirstChild('Game')
local Waypoints = gameFolder:FindFirstChild('Waypoints')
local Model = script.Parent
local point
local waypoints
local nextWaypointsIndex
local reachedConnection
local blockedConnection
local path = pathfindingService:CreatePath({
AgentRadius = 6;
AgentHeight = 5;
AgentCanJump = false;
})
function findTarget()
local humanoid = Model:FindFirstChild('Humanoid')
local HRP = Model:FindFirstChild('HumanoidRootPart')
local maxDistance = 30
local nearestTarget
for index, player in pairs(game:GetService('Players'):GetPlayers()) do
HRP:SetNetworkOwner(player)
if player.Character then
local target = player.Character
local distance = (HRP.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance then
nearestTarget = target
maxDistance = distance
end
if distance < 5 then
print('died')
end
end
end
return nearestTarget
end
function followPath(destination)
local success, errorm = pcall(function()
path:ComputeAsync(Model.PrimaryPart.Position, destination)
end)
if success and path.Status == Enum.PathStatus.Success then
waypoints = path:GetWaypoints()
blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
if blockedWaypointIndex >= nextWaypointsIndex then
blockedConnection:Disconnect()
followPath(destination)
end
if not reachedConnection then
reachedConnection = Model.Humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointsIndex < #waypoints then
nextWaypointsIndex += 1
Model.Humanoid:MoveTo(waypoints[nextWaypointsIndex].Position)
repeat task.wait() until (Model.HumanoidRootPart.Position - waypoints[nextWaypointsIndex].Position).Magnitude <= 1
else
reachedConnection:Disconnect()
blockedConnection:Disconnect()
end
end)
end
end)
nextWaypointsIndex = 2
if waypoints[nextWaypointsIndex] then
Model.Humanoid:MoveTo(waypoints[nextWaypointsIndex].Position)
repeat task.wait() until (Model.HumanoidRootPart.Position - waypoints[nextWaypointsIndex].Position).Magnitude <= 1
end
end
end
local newMapWaypoint
while task.wait() do
local target = findTarget()
if not target then
newMapWaypoint = Waypoints:GetChildren()[math.random(1, #Waypoints:GetChildren())]
followPath(newMapWaypoint.Position)
else
newMapWaypoint = target.HumanoidRootPart
followPath(newMapWaypoint.Position)
end
end