How to detect ray hit at the end of the ray?

I currently got these lines of code set:

if HRP.CFrame.LookVector:Dot(HRP.Velocity) > 0 then
    local RaycastResult = workspace:Raycast(HRP.Position, HRP.CFrame.LookVector*50)
    if not RaycastResult then forwards = true end
elseif HRP.CFrame.LookVector:Dot(HRP.Velocity) < 0 then
        local RaycastResult = workspace:Raycast(HRP.Position, HRP.CFrame.LookVector*-50)
    if not RaycastResult then backwards = true end
end

All this does is detect if the ray intersects and counts that as a hit, however I wanna make it so it only detects the part where the ray ends. I honestly don’t even know if this is possible since I’ve looked everywhere and haven’t found a thing.

1 Like

Guessing your on about getting that part that the ray hits right?

Add a part where if it has a raycastresult then it will do:
local hitpart = RaycastResult.Instance

RaycastResult.Instance is the part that the ray hits. Pretty sure it works with terrain too :slight_smile:

Read up about it here: Raycasting | Roblox Creator Documentation

1 Like

Thank you for helping me out, but unfortunately this is not what I was looking for as I already mentioned that it detects parts that hit it: All this does is detect if the ray intersects and counts that as a hit.
I was looking for a way to make the ray detect only if there are objects hit at the end of the ray or maybe if there are any alternative ways to do that.
But, once again thank you.

Just uh do if RaycastResult.Instance == nil then

That means it hasn’t hit any part

Or if your looking for if it hits a part then

if RaycastResult.Instance ~= nil then

1 Like

are you asking you wanna know what hit the ray when it goes its full length?

1 Like

You want to know if there is something 50 studs out in the direction you are facing, while ignoring anything 30 studs out?
local RaycastResult = workspace:Raycast(HRP.Position * HRP.CFrame.LookVector*49.5, HRP.CFrame.LookVector*50)

1 Like

Yes thank you, this was pretty much what I needed.
However I just found out ray’s only detect surfaces when hit and not if the origin is inside the part.
But thank you, this is what I was looking for.

I just found a solution for this by using region3.
However you can’t change the CFrame of a region3, so I decided to use the RotatedRegion3 Module by EgoMoose.
And now I have my desired result.