Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why wont my :Raycast call return anything?

Asked by 3 years ago

today i started work on a new project, and the tool i was creating needed a raycast. i hadn't used them in a while, so i checked the API, only to see that the ray.new method i used last was tucked away - while the search function instead showed the :Raycast method.

the page all but seemed to say outright that ray.new was deprecated, and :Raycast seemed easier, so i decided to give it a shot.

except that it bricked everything. as i understand it, you fire it with the parameters and it simply returns an object that has parameters you can read individually for the results, but when i use :Raycast it doesn't seem to return anything at all.

heres the code:

--some other irrelevant variables

if tool.Equipped then
uis.InputBegan:Connect(function(input, gameProcessed)
    if gameProcessed then return end
    if input.UserInputType == Enum.UserInputType.MouseButton1 then
        local mouselocation = uis:GetMouseLocation()    
        local newpart = Instance.new("Part")
        newpart.Parent = game.Workspace.PlayerBuildingStuff
        local castres = workspace:Raycast(camera.CFrame.Position, camera.CFrame.LookVector)
        print (castres)
        local partcframe = CFrame.new(castres.Position)
        print (partcframe)
        newpart.CFrame = partcframe
    end
end) end

sorry for the abominable code, i just slapped it together and hit a total wall with this raycast business.

the print (castres) returns nul, and the first call for any value of castres bricks the function with an "attempt to index nil" error.

i really dont know whats wrong. its probably something simple, but if anyone has any advice id really appreciate it. code optimization recommendations included :)

1 answer

Log in to vote
0
Answered by
Necro_las 412 Moderation Voter
3 years ago

The raycast result, in case your "castres", is not the instance nor the position hitted by the ray, its a table with these values inside:

RaycastResult.Instance: The BasePart or Terrain cell that the ray intersected. (nil if there is none)

RaycastResult.Position: The world space point at which the intersection occurred, usually a point directly on the surface of the instance.

RaycastResult.Material: The Material at the intersection point. For normal parts this is the BasePart.Material; for Terrain this can vary depending on terrain data.

RaycastResult.Normal: The normal vector of the intersected face.

0
And when you use it, check if the RaycastResult exists, because it returns nil in some situations. Necro_las 412 — 3y
0
i know that. i am reading the position from the table. in fact just to be sure i tried reading it with a dot operator like i posted and with brackets. they dont work. it all returns nil. this is not my issue. Keleindor 9 — 3y
Ad

Answer this question