I have made a script which should allow me to interact with the nearest brick, however it does not seem to be working as it should as you can see in this gif as it is not interacting with the nearest brick.
https://gyazo.com/919c0f9c30d4ef6c8ac1bb0e1108450a.gif
I have tried by making a table of the distances I get from the HumanoidRootPart to the bricks within my radius and then getting the shortest distance and match that distance with the bricks. However, this does not seem to be interacting with the nearest brick as you can see in the gif attached. I also am wondering if a more efficient way to do so exists.
Here is my script:
local radius = 8
--Get table with distances
function Get_Distances(player, character)
local distances = {}
local models = workspace.Models:GetChildren()
if #models >= 1 then
for i,v in pairs(models) do
local position1 = character.HumanoidRootPart.Position
local position2 = v.Position
local distance = (position1 - position2).magnitude
if distance <= radius then
table.insert(distances, distance)
return distances
end
end
end
end
--Get the nearest Interaction by matching the minimum distances with the table.
function Get_Nearest_Interaction(player, character, distances)
local models = workspace.Models:GetChildren()
for i,v in pairs(models) do
local position1 = character.HumanoidRootPart.Position
local position2 = v.Position
local distance = (position1 - position2).magnitude
if distance == math.min(unpack(distances)) then
return v
end
end
end
--Interacting with the nearest Interaction
game.Players.PlayerAdded:connect(function(player)
player.CharacterAdded:connect(function(character)
spawn(function()
while wait(0.1) do
local Nearest_Interaction
if Get_Distances(player, character) then
local distances = Get_Distances(player, character)
Nearest_Interaction = Get_Nearest_Interaction(player, character, distances)
Nearest_Interaction.BrickColor = BrickColor.Random()
end
end
end)
end)
end)