(pathfinding) humanoids detecting each other as targets

Script

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

function findNearestHead(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 25
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(“Head”)
human = temp2:findFirstChild(“Humanoid”)
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
Head = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return Head
end

while true do
wait(0.1)
local target = findNearestHead(script.Parent.Head.Position)
if target ~= nil then
script.Parent.Humanoid:MoveTo(target.Position, target)
end
end

I am using this script, but the humanoids detect each other and clump up. I am trying to make it so they detect the players only.

Use ``` To Mark Your Script In Top And Bottom

local player = game.Players:GetPlayerFromCharacter(target) if player then return end

This checks if the humanoid is part of a player’s character, if it is, then it returns.

1 Like

Thanks! Which line do i put it on?

between

Between these two should be fine.

Alternatively, because we know we are only looking for Player’s characters, we can just cycle through a list of Player objects and their Characters to determine who our closest target is.

local Players = game:GetService("Players")
local OurHead = script.Parent.Head
local OurHumanoid = script.Parent.Humanoid

local VeryFarAway = math.huge
function FindNearestLivingPlayers(OurPos)
	local ClosestPlayer, ClosestDistance = nil, VeryFarAway
	local PlayerList = Players:GetPlayers()
	
	for _, Player in pairs(PlayerList) do
		local Character = Player.Character
		if Character then
			local Head = Character:FindFirstChild("Head")
			local Humanoid = Character:FindFirstChild("Humanoid")
			if Head and Humanoid and Humanoid.Health > 0 then
				local ThisDistance = (Head.Position - OurPos).magnitude
				if ThisDistance < ClosestDistance then
					ClosestPlayer = Player;
					ClosestDistance = ThisDistance
				end
			end
		end
	end

	return ClosestPlayer, ClosestPlayer and ClosestPlayer.Character.Head or nil
end

while true do
	local TargetPlayer, TargetObj = FindNearestLivingPlayers(OurHead.Position) 
	if TargetObj then
		OurHumanoid:MoveTo(TargetObj.Position, TargetObj)
	end
	wait()
end
1 Like

One thing that’s missing here is the maximum distance a player can be before they aren’t counted anymore. You can change this in 1 line however, can you spot where?

1 Like