Ai not updating targets position

So currently I call the function when a new AI is added to workspace. It then moves to the player if they exist. However, it only updates the character’s positions once the MoveToFinished fired.

https://gyazo.com/c92f2d6017271a375b69d0f118e83441

function movetoPlayer(ai)
	local randomPlayer = game.Players:GetPlayers()[math.random(1,#game.Players:GetPlayers())]
	local character = game.Workspace:FindFirstChild(randomPlayer.Name)
	if character ~= nil then
		local humanoid = ai:FindFirstChild("Humanoid")
		if humanoid ~= nil then
			ai.Humanoid:MoveTo(character.PrimaryPart.Position)
			ai.Humanoid.MoveToFinished:Connect(function()
				if (ai.HumanoidRootPart.Position - character.PrimaryPart.Position).magnitude < 8  then
					wait(1)
					local playerHumanoid = character:FindFirstChild("Humanoid")
					if playerHumanoid ~= nil then
						playerHumanoid.Health = playerHumanoid.Health - 5
						if humanoid.Health >= 1 then
							movetoPlayer(ai)
						end
					end
				else
					ai.Humanoid:MoveTo(character.PrimaryPart.Position)
				end
			end)
		end
	else
		ai:Destroy()
	end
end
1 Like

I put a loop in each ai individually looping once a second and calling the moveto, it then updates that way. But I’d prefer to have a handler than having over 40+ loops at the same time.

1 Like

I’m assuming no one has an answer/way around this problem? I would greatly appreciate it.

Okay so i found the issue so you want to keep the moveto part updated all the time for it to keep following you. What I suggest doing is just make a loop so for every x seconds it will fire another moveto to your characters location. You can’t do it with movetofinished because the ai will wait until it reaches the point before generating another pathway, though this might cause the scripts on the server to run slow though so you could just loop them all in one giant server script

1 Like

I’d first cast a ray to see if the NPC can actually walk towards the player without PathFindingService. Then this could fix it close range and at least make it less noticeable.

1 Like

Yeah, I did that and now they chase the closest person. Thank you, as far as the MoveToFinished goes, I just simply checked the magnitude to determine if they were close enough.
https://gyazo.com/3be7c5b9c77763eaa16228f28df0a378

Thank you.