I noticed that in Dandy’s World, the Twisteds chase the target player for a certain amount of time until they give up.
But when I try to run the script (or even copy it from the tutorials), the NPC ends up chasing the player until it loses sight of them.
Below is the complete script for a better analysis.
local PathfindingService = game:GetService("PathfindingService")
local RS = game:GetService("ReplicatedStorage")
local creature = script.Parent
local humanoid = creature:WaitForChild("Humanoid")
local hpr = creature:WaitForChild("HumanoidRootPart")
hpr:SetNetworkOwner(nil)
local pathParams = {
AgentHeight = 5.125,
AgentRadius = 2.5,
AgentCanJump = false
}
local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Exclude
rayParams.FilterDescendantsInstances = {creature, game.Workspace.Stairs}
local lastPos
local lastTarget
local range = 40
local function canSeeTarget(target)
local origin = hpr.Position
local direction = (target.HumanoidRootPart.Position - hpr.Position).Unit * range
local ray = game.Workspace:Raycast(origin, direction, rayParams)
if ray and ray.Instance then
if ray.Instance:IsDescendantOf(target) then
return true
else
return false
end
else
return false
end
end
local function findTarget()
local players = game.Players:GetPlayers()
local maxDistance = range
local nearestTarget
for index, player in pairs(players) do
if player.Character then
local target = player.Character
local distance = (hpr.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance and canSeeTarget(target) then
nearestTarget = target
maxDistance = distance
end
end
end
return nearestTarget
end
local function getPath(destination)
local path = PathfindingService:CreatePath(pathParams)
path:ComputeAsync(hpr.Position, destination.Position)
return path
end
local function attack(target)
local distance = (hpr.Position - target.HumanoidRootPart.Position).Magnitude
local debounce = false
if distance > 10 then
humanoid:MoveTo(target.HumanoidRootPart.Position)
else
if debounce == false then
debounce = true
target.Humanoid.Health -= 10
task.wait(3)
debounce = false
end
end
end
local function walk(destination)
local path = getPath(destination)
if path.Status == Enum.PathStatus.Success then
for index, waypoint in pairs(path:GetWaypoints()) do
path.Blocked:Connect(function()
path:Destroy()
end)
local target = findTarget()
if target and target.Humanoid.Health > 0 then
lastTarget = target
lastPos = target.HumanoidRootPart.Position
attack(target)
creature.Humanoid.WalkSpeed = 30
break
else
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait()
humanoid.WalkSpeed = 12
end
end
else
return
end
end
local function patrol()
local waypoints = workspace.WayPointsNew:GetChildren()
local randomNum = math.random(1, #waypoints)
walk(waypoints[randomNum])
end
while task.wait() do
patrol()
end
Any tips for the script would also be helpful
.