I am working on a NPC and I have written some scripts for patrolling and some scripts for chasing a player and doing damage. But when I test it and get close to the NPC, it keeps on patrolling and not chasing me. However, it does do the damage when I get close. Please help me and thank you.
Here is my script:
local npc = script.Parent
local npcHumanoid = npc:WaitForChild("Humanoid")
local PointA = game.Workspace.PointA
local PointB = game.Workspace.PointB
npcHumanoid:MoveTo(PointA.Position)
PointA.Touched:Connect(function(hit)
if hit.Parent.Name == "NPC" then
npcHumanoid:MoveTo(PointB.Position)
end
end)
PointB.Touched:Connect(function(hit)
if hit.Parent.Name == "NPC" then
npcHumanoid:MoveTo(PointA.Position)
end
end)
function findNearestTorso(position)
local list = game.Workspace:GetChildren()
local torso = nil
local humanoid = nil
local distance = 1000
local temp = nil
local temp2 = nil
local damage = 20
local check = script.Parent.Check
for i = 1, #list do
temp2 = list[i]
if temp2.className == "Model" and temp2 ~= script.Parent then
temp = temp2:FindFirstChild("Torso")
humanoid = temp2:FindFirstChild("Humanoid")
if temp and humanoid and humanoid.Health > 0 then
if (temp.Position - position).magnitude < distance then
torso = temp
distance = (temp.Position - position).magnitude
end
end
end
end
if distance <= 4 then
humanoid:TakeDamage(damage)
end
end
while true do
wait(1)
local target = findNearestTorso(script.Parent.Torso.Position)
if target then
script.Parent.Humanoid:MoveTo(target.Position, target)
end
end
