Not exactly, I already got a loop that finds the parts that are visible to the player, however I’m trying to find which of those parts are the closest to the center of the screen. This post: Check if object is near the center of the screen?
Is kinda what I’m going after
Here you go. Let me know if you have any troubles.
local player = game.Players.LocalPlayer
local camera = workspace.CurrentCamera
local PartsTable = {}
local CamPos = camera.CFrame.p
local ClosestDistance = math.huge
local ClosestPart = nil
for i = 1, #PartsTable do
local Part = PartsTable[i]
local Distance = (CamPos - Part.Position).Magnitude
if ClosestDistance > Distance then
ClosestDistance = Distance
ClosestPart = Part
end
end
print(ClosestPart.Name)
In the following picture the Part in the black circle is closest to screens center, The other parts are in the table with ClosestParts, I’m trying to get the distance between all the parts (ClosestParts) and find the one that is the closest to the screen center. In this case the one in the black circle.
Recorded this video using this script. I’m not sure how to get only the parts in the camera view, but I’m sure you can find that on another thread.
Edit: Just reread and saw that you already have a script to get the parts you need to loop through.
local player = game.Players.LocalPlayer
local camera = workspace.CurrentCamera
local PartsTable = game.Workspace.Parts:GetChildren()
while true do
wait()
local CamPos = camera.CFrame.p
local ClosestDistance = math.huge
local ClosestPart = nil
for i = 1, #PartsTable do
local Part = PartsTable[i]
Part.Color = Color3.new(0,0,0)
local Distance = (CamPos - Part.Position).Magnitude
if ClosestDistance > Distance then
ClosestDistance = Distance
ClosestPart = Part
end
end
ClosestPart.Color = Color3.new(1,1,1)
end
You can get the 2d point on the screen by using a method from the camera WorldToViewportPoint, then using magnitude to get the distance from the center of the screen:
local Camera = workspace.CurrentCamera
local parts = {} -- table of all the parts
local screenCenter = Camera.ViewportSize / 2 -- Getting the center of the screen
local closestPosition = math.huge -- The current closest position a part is from the center
local closestPart -- Closest part
for _, Part in pairs(parts) do
local positionOnScreen = Camera:WorldToViewportPoint(Part.Position)
local magnitude = (screenCenter - screenCenter).Magnitude -- Getting the distance from the center of the screen
if magnitude < closestPosition then -- Checking if the part is closer to the center than the previous parts checked
closestPosition = magnitude
closestPart = Part
end
end
print(closestPart) -- Prints out the closest part from the center of the screen