How would I make a AI move to a certain target if they are in a certain amount of studs? And the AI would change to the closest target if another target enters the range
I have no clue how to do this and I would very appreciate it if you would help me!
I don't know exactly, but I saw it being done. There is a thingy called magnitude
that returns the distance from point A to point B, so you could have a script that is similar to the following one:
local target = nil --The AI's current target local dis = 20 --The max distance while true do wait(1) local cpos = script.Parent.Position --The AI's current position local nearest = math.huge() --Nearest distance from player to AI local players = game.Players:GetChildren() for _, player in ipairs(players) do local chara = player.Character if chara ~= nil then --Checks if player is alive local torso = chara:FindFirstChild('Torso') --Finds R6 torso if torso == nil then torso = chara:FindFirstChild('UpperTorso') end --Finds R15 torso local mag = (cpos - torso.Position).magnitude --Finds distance if mag < nearest and mag < dis then --Checks if the player is nearer then the last one checked nearest = mag target = player --Sets target end end end end
I wrote this really quickly, so I didn't test it. (May not work) Try altering this
Accept if helped