How can I find the first item a raycast hits?

when I shoot a raycast that hits lets say 5 items, how can I find which of them it hit first?

You can use RaycastResult.Instance to find the part in which the ray hit.

If I am correct raycasts cant hit multiple items, they can only hit one, so unless you are firing multiple raycasts you will only get one item

Just sort them in the order that they were fired in, and then iterate through their results to find an Instance, if there is one, exit the function, something like this:

local t = {} -- to store all our results
local firstIndex; -- this to help find the first index

for i = 1,AmountOFRaysFiring do -- this will iterate 5 times
    if not t[i - 1] and not firstIndex then
        -- this checks to see if there is no index before the current
        -- it also checks if it hasn't been chosen yet
        firstIndex = i; -- apply firstIndex variable
        -- this means that something hit
    end
    
    local result = workspace:Raycast(Position, Direction, Params); -- Cast Ray
    if not result then continue end -- ignore if no result
    
    t[i] = result.Instance -- declare index inside table with Instance
    -- RaycastResult will always return nil if it hadn't it anything
end

return t[lastIndex] -- return whatever data was collected
-- if it returns nil, nothing has hit at all.

But that depends on how many you are firing, because a ray will only return one result (which means only one instance). Unless you are refering to if something is overlapping, you would have to find the closest object, or pick a random one

Raycasts fire instantly so im guessing the closest you’ll get to figuring out which one hit “first” is which RayResult has the lowest distance.

Raycasts will only hit one item.

1 Like