How to find the closest item to a player

I was wondering how to detect which coin was closest to the player, and tween them in order from closest to the player, to furthest from the player for better effects. Here is my script now.

-- // Services
local TweenService = game:GetService("TweenService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- // Variables
local player = game.Players.LocalPlayer
local character = player.Character
local lowerTorso = character:WaitForChild("LowerTorso")
local currencyHolder = player.PlayerGui.CurrencyHolder
local GetCoin = ReplicatedStorage:WaitForChild("GetCoin")
local CoinCollectSound = script:WaitForChild("Coin")
-- Info for the tweens
local infotween = TweenInfo.new(
	0.08,
	Enum.EasingStyle.Linear,
	Enum.EasingDirection.Out,
	0,
	false,
	0,
	true
)
local infotween2 = TweenInfo.new(
	0.10,
	Enum.EasingStyle.Linear,
	Enum.EasingDirection.Out,
	0,
	false,
	0,
	true
)
-- Currency changing function
spawn(function()
	while true do
		wait()
		--Changes coin text to amount of coins(need to debug some things)
		currencyHolder.CoinsAmount.Text = player.PlayerStats.Coins.Value
	end	
end)

-- Function that checks if coin is close enough to player, and if they are it attracts the coin(s) and gives the player coins.
spawn(function()
	while true do
		wait(0.0000000001)
		-- Getting all the coins
		for i, Coins in pairs(game.Workspace.Coins:GetChildren()) do
			-- Checking if the coins dont exist
			if Coins == nil then
				return
			end
			-- Checking if the coins exist
			if Coins ~= nil then
				wait()
				-- Checking the distance between the player, and the coins
				if (lowerTorso.Position - Coins.Position).Magnitude <= 19 then
					-- Goals when attracting the coin
					local goal = {

						Position = lowerTorso.Position,
						Transparency = 1
					}

					-- Plays the tween, that attracts the coins, and makes the coins go transparent
					task.spawn(function()
						local tween = TweenService:Create(Coins, infotween, goal)
						local tween2 = TweenService:Create(Coins:WaitForChild("Coin_UI").Coin_Label, infotween2, {ImageTransparency = 1})
						-- Plays coin attracting tween
						tween:Play()
						-- Plays going transparent tween
						tween2:Play()
						-- Waits until the tween is completed to continue the script
						tween2.Completed:Wait()
						tween.Completed:Wait()
					end)
					-- Fires the server, and destroys the coins on the server
					GetCoin:FireServer(Coins)
					-- Adds one coin to players stats(need to debug)
					player.PlayerStats.Coins.Value += 1
					CoinCollectSound:Play()
				end
			end
		end
	end
end)

1 Like
local closeEnoughCoins = {}
for _, coin in ipairs(game.Workspace.Coins:GetChildren()) do
    if (coin.Position - lowerTorso.Position).Magnitude <= 19 then
        table.insert(closeEnoughCoins, coin)
    end
end

table.sort(closeEnoughCoins, function(value1, value2) 
    if (value1.Position - lowerTorso.Position).Magnitude < (value2.Position - lowerTorso.Position).Magnitude then 
        return true 
end))

for _, coins in ipairs(closeEnoughCoins) do
    					-- Goals when attracting the coin
					local goal = {

						Position = lowerTorso.Position,
						Transparency = 1
					}

					-- Plays the tween, that attracts the coins, and makes the coins go transparent
					task.spawn(function()
						local tween = TweenService:Create(Coins, infotween, goal)
						local tween2 = TweenService:Create(Coins:WaitForChild("Coin_UI").Coin_Label, infotween2, {ImageTransparency = 1})
						-- Plays coin attracting tween
						tween:Play()
						-- Plays going transparent tween
						tween2:Play()
						-- Waits until the tween is completed to continue the script
						tween2.Completed:Wait()
						tween.Completed:Wait()
					end)
					-- Fires the server, and destroys the coins on the server
					GetCoin:FireServer(Coins)
					-- Adds one coin to players stats(need to debug)
					player.PlayerStats.Coins.Value += 1
					CoinCollectSound:Play()
end
1 Like

I tried adding that, but it attracts all the coins to me at once, and crashes my studio.

It also gives me way more coins than the existing ones

Take the task.spawn out. Taking this out will make it wait for the coin to be collected before it picks up the next one.