local npc = script.Parent
local debounce = false
local distanceInformation = script.Parent:WaitForChild("Information").Distance
npc.Humanoid.Touched:Connect(function(hit)
if hit and game.Players:GetPlayerFromCharacter(hit.Parent) then
if debounce == false then
debounce = true
hit.Parent.Humanoid:TakeDamage(10) -- U SHOULD TO CHANGE THIS!!!
wait(.25) -- AND THIS!!!
debounce = false
end
end
end)
function FindPlayer(Position)
local list = game.Workspace:GetChildren()
local torso = nil
local distance = 50 -- CHANGE THIS TOO!!!
local HRP = nil
local humanoid = nil
local player = nil
for i = 1, #list do
player = list[i]
if (player.ClassName == "Model") and (player ~= script.Parent) then
HRP = player:FindFirstChild("HumanoidRootPart")
humanoid = player:FindFirstChild("Humanoid")
if (HRP ~= nil) and (humanoid ~= nil) and (humanoid.Health > 0) then
if (HRP.Position - Position).Magnitude < distance then
torso = HRP
distance = (HRP.Position - Position).Magnitude
distanceInformation.Value = distance -- CHANGING DISTANCE!!!
end
end
end
end
return torso
end
while wait(1) do
local target = FindPlayer(script.Parent.HumanoidRootPart.Position)
npc.Humanoid.Health = 100
if target ~= nil then
script.Parent.Humanoid:MoveTo(target.Position, target) -- MOVING NPC TO US
end
end
So this is my script that makes the enemy follow you and hit you.
But I have a problem, namely that if he did not find me in the right distance, he just goes to another npc who also has a humanoid and everything else
And he actually sees the other npc as an enemy and follows him.
And I want him not to move if he doesn’t find me.
Instead of looping through Workspace for nearby players, you can instead use a player’s character by looping through the Players service. This will stop your NPC script from targeting other NPCs, since they are not players. This will also increase efficiency and memory usage as the Players service will have significantly less objects that would have needed to be looped through compared to the Workspace.
local playerList = game:GetService("Players"):GetPlayers()
for i, plr in pairs(playerList) do
local playerCharacter = plr.Character or plr.CharacterAdded:Wait()
if playerCharacter then
-- Continue from here
end
end
function FindPlayer(Position)
local playerList = game:GetService("Players"):GetPlayers() local torso = nil
local distance = 50 -- CHANGE THIS TOO!!!
local HRP = nil
local humanoid = nil
local player = nil
for i, plr in pairs(playerList) do
local playerCharacter = plr.Character or plr.CharacterAdded:Wait()
if playerCharacter then
HRP = player:FindFirstChild("HumanoidRootPart")
humanoid = player:FindFirstChild("Humanoid")
if (HRP ~= nil) and (humanoid ~= nil) and (humanoid.Health > 0) then
if (HRP.Position - Position).Magnitude < distance then
torso = HRP
distance = (HRP.Position - Position).Magnitude
distanceInformation.Value = distance -- CHANGING DISTANCE!!!
end
end
end
end
return torso
end