Monster Chasing AI getting confused

Hi!!! This was my first time making an AI that pathfinds to a player and kills them after catching them. It works just as I want it to with a single player. But whenever there’s more than one players, the AI seems to get kinda confused and does a little dance between the players. Here is the script:

local NPC = game.Workspace.Monster
local PFS = game:GetService("PathfindingService")

local path = PFS:CreatePath()

while wait() do
	for i, v in pairs(game.Workspace:GetDescendants()) do
		if v.Name == "Humanoid" and v.Parent ~= NPC then
			path:ComputeAsync(NPC.HumanoidRootPart.Position, v.Parent.HumanoidRootPart.Position)
			local waypoints = path:GetWaypoints()
			for i, waypoint in pairs(waypoints) do
				NPC.Humanoid:MoveTo(waypoint.Position)
			end
		end
	end
end

What I want it to do is basically stick to the closest player. Thanks!

1 Like

Yeah you may want to detect which player is closer because it will continually switch targets otherwise.

2 Likes

How can I do it? I’m a little stuck here

Look it up how yo find the distance between two parts on You-Tube. I can’t seem to find a devhub article on it.

1 Like

Okay, so I’m gonna be trying to use magnitude, 'cause I did learn it during my scripting lessons and that seems to be the most appropriate method. If I succeed, I’ll be posting the script here as the solution.

--you can use the pythagorean theorem to find the distance between things

--put this in a for loop for all players in the game
local distanceBetween = monstersPosition - player position
local cal1 = math.sqrt(distanceBetween.X * distanceBetween.X + distanceBetween.Z * distanceBetween.Z)
local cal2 = math.sqrt(cal1 * cal1 + distanceBetween.Y * distanceBetween.Y)
print(cal2)
1 Like

Okay so I tried using magnitude to get the closest player to the monster and it works perfectly lmao

local NPC = game.Workspace.Monster
local PFS = game:GetService("PathfindingService")
local path = PFS:CreatePath()
local waypoints

while wait() do
	local Target
	local TargetDistance = math.huge
	for i, v in pairs(workspace:GetDescendants()) do
		if v.Name == "Humanoid" and v.Parent ~= NPC then
			local mag = (NPC.HumanoidRootPart.Position - v.Parent.HumanoidRootPart.Position).Magnitude
			if mag <= TargetDistance then
				TargetDistance = mag
				Target = v.Parent
			end
		end
	end
	if Target ~= nil then
		path:ComputeAsync(NPC.HumanoidRootPart.Position, Target.HumanoidRootPart.Position)
		local waypoints = path:GetWaypoints()
		for i, waypoint in pairs(waypoints) do
			NPC.Humanoid:MoveTo(waypoint.Position)
		end
	end
end
2 Likes