I have been trying everything. Nothing has worked..

What I want to do is make the AI chase the nearest player instead of the crystal if a player is in range, BUT even if I am touching the AI it's target is still the crystal.

I am not looking for a script, just a way that I could do this OR what I could edit in my script.

local foundplayer = false

function getNearestTorso()
	for i, v in pairs(workspace:GetChildren()) do
		if v.ClassName == "Model" then
			if v:FindFirstChild("Humanoid") then
				if v ~= script.Parent then
					local dis = (script.Parent.Torso.CFrame.p - v.HumanoidRootPart.CFrame.p).magnitude
					
					if dis < 10 then
						return v
					else
						return nil
					end
				end
			end
		end
	end
end

while wait(0.1) do
	if not foundplayer then
		foundplayer = false
		script.Parent.CurrentTarget.Value = workspace.Crystal.EnemyMoveTo
		
		local start = script.Parent.Torso.Position
		local path = game:GetService("PathfindingService"):ComputeRawPathAsync(start, script.Parent.CurrentTarget.Value.Position, 20)
		local points = path:GetPointCoordinates()
		
		for _, point in ipairs(points) do
			script.Parent.Humanoid:MoveTo(point)

			repeat
				local distance = (point - script.Parent.Torso.Position).magnitude
				wait()
			until foundplayer == true or distance < 3
			
			if foundplayer then
				break
			end
		end
		
		script.Parent.Animations.Walking.Value = true
	end
end

while wait() do
	local nearest = getNearestTorso()
	
	if nearest then
		print(nearest.Name)
		foundplayer = true
		script.Parent.CurrentTarget.Value = nearest
		
		script.Parent.Animations.Walking.Value = true
		
		local start = script.Parent.Torso.Position
		local path = game:GetService("PathfindingService"):ComputeRawPathAsync(start, script.Parent.CurrentTarget.Value.HumanoidRootPart.Position, 20)
		local points = path:GetPointCoordinates()
		
		for _, point in ipairs(points) do
			script.Parent.Humanoid:MoveTo(point)

			repeat
				distance = (point - script.Parent.Torso.Position).magnitude
				wait()
			until distance < 3
		end
	end
end

2 comments

1

The second while loop is never reached, because the first one is infinite.

0

oh.... well... thanks lol