Sentry Cannon Nearest Player Detection

Okay, I’m doing a tank that controls by AI.

Now, I don’t know how to make the tank to aim the nearest player when the tank can see directly to the player and distance < 350

Any idea?

2 Likes

Have you ever heard of a magnitude check?

local distance = (Player.Position - Tank.Position).Magnitude

This returns the distance between the player and the tank. Just loop through each of the players to find the nearest one in range and boom.

1 Like

I know how to use it, how can I know which one is the nearest?
I mean how to compare all of the distance between tank and players.

Here’s a function that should work, call it whenever you need to find the nearest head. (It returns the entire character though), requires a Character argument so just send the Sentry Cannon as that and make sure it has a “Head” to gauge its distance.

local function findNearestHead(Character)
	local listey = game.Players:GetChildren()
	local list = {}
	for z,b in pairs(listey) do
		table.insert(list,z,b.Character)
	end
	local dist = 350
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x] 
		if (temp2.className == "Model") and (temp2 ~= Character) then
			temp = temp2:findFirstChild("Head")
			pcall(function()
				if (temp.Position - Character.Head.Position).magnitude < dist then
					target = temp.Parent
					dist = (temp.Position - Character.Head.Position).magnitude
				end
			end)
		end
	end
	if target == nil then return end
	if temp == nil then return end
	dist = (temp.Position - Character.Head.Position).magnitude
	return target,(target.Head.Position - Character.Head.Position).magnitude
end

Let me try by using table :slight_smile: