How does one convert the old ray cast method, to the new one?

So I have some basic ray cast code which fires a ray and deals damage shown below.

CODE SHOWN HERE
local ray = Ray.new(character.HumanoidRootPart.Position, character.HumanoidRootPart.CFrame.LookVector * 35)
local hit = workspace:FindPartOnRay(ray, character)
			
if hit and hit.Parent:FindFirstChild("Humanoid") then
    local target = hit.Parent
				
    target.Humanoid:TakeDamage(0.6) -- this was in a while loop, hence the low damage.
end

Now then I’d like to convert that old code to the new ray casting method shown in the Developer Hub.

However I feel that it’s kinda bloated which was why I was so on the fence learning it, and I’m having some trouble applying it in real code which is why I’m asking for some sample code from someone, that isn’t bloated.

By “bloated” I mean the least amount of variables possible that still make the code easy to read. I don’t wanna define 6+ variables to do some basic raycasting.

You would just construct a RaycastParams object first.

local params = RaycastParams.new()
params.FilterDescendantsInstances = { character }
params.FilterType = Enum.RaycastFilterType.Blacklist -- you want to ignore it

Then you want to perform the raycast.

local result = workspace:Raycast(
    character.HumanoidRootPart.Position, 
    character.HumanoidRootPart.CFrame.LookVector*35,
    params
)

Since WorldRoot:Raycast returns nil when the ray didn’t hit anything, you now need to verify it did.

if result then

end

The part that was hit by the ray is contained in the Instance property of the RaycastResult returned by WorldRoot:Raycast.

    local humanoid = result.Instance.Parent:FindFirstChild("Humanoid")

Now just check if that exists too.

    if humanoid then

    end

Then just deal the damage!

        humanoid:TakeDamage(0.6)

I’ve changed up your example code so that it’s a little less bloated.

CODE
local params = RaycastParams.new()
params.FilterDescendantsInstances = {character}
params.FilterType = Enum.RaycastFilterType.Blacklist
		
local hit = workspace:Raycast(character.HumanoidRootPart.Position, character.HumanoidRootPart.CFrame.LookVector * 10, params)
		
if hit and hit.Instance.Parent:FindFirstChild("Humanoid") then
    local target = hit.Instance.Parent -- I create a variable since I usually load animations into the target and do a variety of other things

    -- when just getting what you hit you can use, "hit.Instance"
    -- for example, adding a body velocity into a right arm if the ray hit it.
    target.Humanoid:TakeDamage(10)
end)	

About the best I can do with this, I hope anyone who looks at this can use it for their projects if they ever need raycasting. :grinning: