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

Why does my NPC follow script has a problem?

I want to create a crime game where if you commit a crime wanted is a boolvalue and it is in the humanoid. Wanted only activate if you commit a crime. When the police officers are spawned on the same area they attack each other, how can I stop this they kept on following each other if not they will follow me and I just want them to follow me without changing the humanoid name to something else cause I make a lot of weapons that involved players humanoid and that's a lot of work to do.

local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = script.Distance.Value
	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("Torso")
			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(0.1)
	local target = findNearestTorso(script.Parent.Torso.Position)
	for i,v in ipairs(game.Workspace:GetChildren()) do
		if v:findFirstChild("Humanoid") then
			if v.Humanoid:findFirstChild("wanted") then
			if v.Humanoid.wanted.Value == true then
				if target ~= nil and  v.Humanoid.wanted.Value == true then
	script.Parent.Humanoid:MoveTo(target.Position, target)
	else
			
				end
				end
				end
		end
	end

end

2 comments

0

:GetChildren?

0

^^

1 answer

You appear to be trying to find a suitable target 2x! First when you call "findNearestTorso" (which needs to have code added to determine whether a model is a fellow police officer or not - ex, you could add a Folder/BoolValue/whatever with the name "PoliceOfficer" to police officer NPCs so that your script can tell difference), then again in lines 30+. The if checks on lines 32-33 should be moved to findNearestTorso and then the for loop on line 30 removed (keeping lines 34-35).

1 comment

0

thanks

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