Okay so this is a script that detects the closest part to the player but a little differently.
It only detects the parts in front of the player and from a specific range. I want make it so parts can’t be detected under the player’s character.
local RunService = game:GetService("RunService")
local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoidRootPart = character:WaitForChild("HumanoidRootPart")
local closestPart
local currentValue = 1
for i, v in pairs(workspace.Connections:GetChildren()) do -- This is just giving the parts unique names
if v:IsA("BasePart") then
v.Name = "Connection"..currentValue
currentValue = currentValue + 1
end
end
local function insert(tbl, ...)
for _, value in ipairs({ ... }) do
table.insert(tbl, value)
end
end
RunService.RenderStepped:Connect(function()
wait(0.01)
local inRange = {}
for i, child in ipairs(workspace.Connections:GetChildren()) do
local range = (child.Position - humanoidRootPart.Position).Magnitude
local characterToPart = (child.Position - humanoidRootPart.Position).Unit
local playerLook = humanoidRootPart.CFrame.LookVector
local dotProduct = characterToPart:Dot(playerLook)
if dotProduct < 0.7 or range > 700 then
child.BrickColor = BrickColor.new("Really red") -- Not In FOV
closestPart = nil
else
if range <= 700 then
child.BrickColor = BrickColor.new("Dark blue") -- In FOV
local magnitude = (child.Position - humanoidRootPart.Position).Magnitude
insert(inRange, {Magnitude=magnitude,Name=child.Name})
end
end
end
if (next(inRange) ~= nil) then
table.sort(inRange, function(a,b)
if a.Magnitude < b.Magnitude then
return true
else
return false
end
end)
closestPart = workspace.Connections:FindFirstChild(inRange[1].Name)
closestPart.BrickColor = BrickColor.new("Dark green")
end
end)