Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How can I stop NPC from attacking each other?

To star with I am not good at cod at all. The NPC works fine till in the range of another NPC. When in range it stops attacking the player and go's for its brother NPC. Here is the cod

local larm = script.Parent:FindFirstChild("HumanoidRootPart")
local rarm = script.Parent:FindFirstChild("HumanoidRootPart")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 10000
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent) then
			temp = temp2:findFirstChild("HumanoidRootPart")
			human = temp2:findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end




while true do
	wait(math.random(1,5))
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil then
		script.Parent.Humanoid:MoveTo(target.Position, target)
	end

end

1 comment

1

Don't come on this site with free model code, expecting for it to be fixed.

1 answer

Instead of using

local list = game.Workspace:children()

Use

local list = game.Players:GetChildren()

and test these

temp = temp2:findFirstChild("HumanoidRootPart")
human = temp2:findFirstChild("Humanoid")

Like this,

for _,test in pairs(list) do
	if test.Character then
		local hrp = test.Character:FindFirstChild("HumanoidRootPart")
		local humanoid = test.Character:FindFirstChild("Humanoid")
		if hrp and humanoid then
			if (hrp.Position - YOU.position).magnitude then
				...
			end
		end
	end
end

1 comment

0

That wasn't his code anyway

This discussion is preserved as it was. New answers, comments, and votes are closed.