I am trying to make it so that only the object that is closest to the middle of the screen is detected, but whenever I do it, all 3 or 2 are activated
my code here:
while wait() do
if Enabled.Value == true then
for _, blocks in pairs(workspace.partstest:GetChildren()) do
if blocks.Name ~= ACTUALPLAYER.Value and blocks:IsA("Part") then
local part = blocks
local worldPoint = blocks.Position
local vector = camera:WorldToScreenPoint(worldPoint)
local delta = Vector2.new(vector.X, vector.Y)-camera.ViewportSize/2
local datos = worldPoint
local inCamX = delta.Magnitude<camera.ViewportSize.X/5
if inCamX and vector then
blocks.Material = Enum.Material.Neon
blocks.BrickColor = BrickColor.new(0, 255, 0)
else
if not inCamX or not vector then
blocks.Material = Enum.Material.Plastic
blocks.BrickColor = BrickColor.new(255, 255, 255)
end
end
end
end
end
end
How can I make it only detect the one closest to the middle of the screen?
You can have a table that stores sub-tables which include the object and the distance of the object onscreen to the center of the screen, then sort the table from the closest to the farthest:
local parts = {}
while true do
if not Enabled.Value then return end
for _, block in ipairs(workspace.partstest:GetChildren()) do
if block.Name == ACTUALPLAYER.VALUE or not block:IsA("Part") then continue end
local pos = camera:WorldToViewportPoint(block.Position)
local center = camera.ViewportSize / 2
table.insert(parts, {
Block = block;
Distance = (center - Vector2.new(pos.x, pos.y)).Magnitude
})
end
table.sort(parts, function(a, b)
return a.Distance < b.Distance
end)
local closest_part = parts[1].Block
end
You can omit the 3rd (Z-axis) component of this returned Vector3 value as it just represents the depth from the screen to the world point, the X and Y axis components are more important here.