Snapping camera to closest vector3 position

Hi there!

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?

image
In the image above you see what im trying to achieve. The part on the right side here should be returned.

Thanks in advance!

Hmm… is the camera like a free-cam or attached to a character?

Attached to the character. Just the normal Custom Camera enum.

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.

1 Like

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.

So you would be looking for something more like finding the closest part to a line going through the camera that also has the direction of the camera?

-- 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

but its also possible to use

https://developer.roblox.com/en-us/api-reference/function/Camera/WorldToViewportPoint

while i have not benchmarked it im guessing doing it the angle method will be faster then using the WorldToViewportPoint function

2 Likes