I have a script always makes a gun fire at a dummy, but how would I make the gun to fire at the nearest dummy (eventually a player). I think I can set a variable to the distance of every player, but I don't know how to program for the script to pick the smallest one. Any help?
Hello, To my knowledge, the easiest way to do this would be to iterate between all players in the game and their characters. Here's an example:
local plrs = game:GetService("Players") function getClosestPlayer(location) -- Function to get the information. Location is the location to find the closest player from. local closestDistance = math.huge -- The closest player distance. This should start at a super big value to make sure all players are under that range, hence I use math.huge (infinity). local closestCharacter = nil -- Track the closest character for i, player in pairs(plrs:GetPlayers()) do -- Iterate over all players in the game. if player.Character then -- Make sure the player has a character. local distance = (player.Character-location).magnitude -- Find the distance between the two points. An easier way to calculate the distance formula. if distance < closestDistance then -- Is the distance between these two less than the closest distance so far? closestDIstance = distance -- Yes! Now set the closestDistance to this distance. closestCharacter = player.Character -- Set the closestCharacter to the player's character. end end end return closestCharacter, closestDistance end -- Example of how to use the function: local character, distance = getClosestPlayer(Vector3.new(0,0,0) -- Get the closest player to 0,0,0 print(character,distance)
Hope this helps (and hope there aren't any errors, lol).