Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

AI not detecting the nearest target?

Whenever i put a two target is is near the ai the ai got confused where to go, it's attempting to go to both at the same time that is causing the model(ai) to shake

local a = 100
	
for i = 1, #ore do
		
	 local dist = (ore[i].Ore.Position - eng.Position).magnitude 
		if dist < a then
			a = dist
		end
		end


	for i = 1, #ore do
		
	 if(ore[i].Ore.Position - eng.Position).magnitude == a then
			target = ore[i]
			
		end
		end

4 comments

0

What is "eng?" In the script you're presenting, it isn't defined anywhere. XP

0

it is on the top of script, this is a long script

0

Make a pastebin or a Codeshare.io with the full code

1 answer

The problem is in the full script in the line if c[i]:FindFirstChild("Htitanium") ~= nil and c[i] ~= target and c[i].Htitanium.Health > 0 then. You are telling your found function to ignore the target while it considers the next target. You should delete the c[i] ~= target part so that your drone will consider keeping its current target.

Also, you can remove the third for loop in your found function by merging it into the second:

	local a = 100
	for i = 1, #ore do
		local dist = (ore[i].Ore.Position - eng.Position).magnitude 
		if dist < a then
			a = dist
			target = ore[i]
		end
	end

It's okay if target is changed several times in this loop because it will always settle on the closest target by the time the for loop is done and no other function nor script will run while this is occurring -- in lua, only one thing runs at a time.

If you want the target to be lost if they get out of the 100 stud range, then you should add target = nil right after local a = 100.

One last note is that you have a maxDistance argument which you don't use. You should either delete the argument or add support for it by saying local a = maxDistance or 100 (which means that if you do found(150), the drone will look within 150 studs, but if you say found(), maxDistance will be nil and 100 will be used by default).

This discussion is preserved as it was. New answers, comments, and votes are closed.