Help with an NPC targeting turret

I am planning to make a turret that targets NPCs and avoids the players, but I am very unsure of how to do this. I want the turret to look for multiple different potential entities but I do not know how I would make a turret look for multiple at once. I am not asking for a script or anything of that kind, but I would appreciate any insight on the process of creating this.

1 Like

Do you mean like find the closest player to the turret?

Find the first NPC within range and then keep on that NPC targeted until they are “dead” or out of range.

1 Like

Here, try this out:

local function FindTarget(char: Model)
	local primary = char.PrimaryPart
	local target, distance = nil, nil

	for _,v: Model in ipairs(workspace:GetDescendants()) do
		if v:IsA("Model") and primary then
			local targetHRP = v.PrimaryPart
			local targetHum = v:FindFirstChildWhichIsA("Humanoid")
			local mag = (primary.Position - targetHRP.Position).Magnitude

			if v and targetHRP and targetHum and targetHum.Health ~= 0 then
				if v and distance then
					if mag < distance then
						target = targetHRP
						distance = mag
					end
				else
					target = targetHRP
					distance = mag
				end
			end
		end
	end

	return target, distance
end
1 Like

Could you explain a little bit of it because I might need to fit it to my exact situation?

1 Like

This loops through workspace, checks for any characters (with humanoids). Then they check the distance between the turret and the target. And if…

mag < distance

You put that target in the target and distance variables.

Then the cycle repeats until eventually… you’ll get the closest target to the turret.