I’m trying to make a system where if you hold the mousebutton a script will detect the closest part that the camera is currently facing. I’m kinda struggling with the last part, how would i basically detect what part is the closest to the point the camera is looking at? Are there any methods for this?
In the image above you see what im trying to achieve. The part on the right side here should be returned.
You could try raycasting from the camera, taking the point where the ray hits something in 3d space and choosing the closest part to that point. Not sure if that’s what you are looking for, though.
That is kinda tricky tho, if the player is looking towards a spot very far away it will still select that part and not the part that’s actually very close to them.
-- get the camera position
local cameraPosition = game.Workspace.CurrentCamera.CFrame.Position
-- get the direction the camera is facing
local cameraLookVector = game.Workspace.CurrentCamera.CFrame.LookVector
-- get half of the cameras field of view in radians
local fov = math.rad(game.Workspace.CurrentCamera.FieldOfView) / 2
-- this is where we will store the closest part as we loop all parts
local closestPart = nil
-- we will use this to keep track of how close the current part is
local magnitude = math.huge
-- loop all parts
for i, part in ipair(game.Workspace.Parts:GetChildren()) do
-- create a vector3 that will tell us the direction and distance to the part from the camera position
local direction = part.Position - cameraPosition
-- if the distance is grater then are previously found part then skip this part
if magnitude <= direction.Magnitude then continue end
-- work out the angle of the part to the direction the camera is facing
local angle = math.acos(cameraLookVector:Dot(direction.Unit))
-- if the angle is grater then the camera FOV then skip this part
if angle > fov then continue end
-- all checks have passed we have found are new closest part lets save it
closestPart = part
magnitude = direction.Magnitude
end
-- this is the closest part and its distance
print(closestPart.Name, magnitude)
in this code i use the angle and fov to work out if a part is in view