Raycasting Help

Hello, thank you for taking the time to try and help me.

I am creating a Placing system, I am Raycasting the players mouse position using UserInputService:GetMouseLocation() and Camera:ViewportPointToRay().

If a ray hits a part then I want to instance a part at that position. If it does not, then I want the part to be instanced at the max distance in the direction of the players mouse. How would I go about doing this?

I have looked for other solutions similar to my problem and I couldn’t find anything related.

Here is the current code inside a local script:

local MaxDistance = 99
local MouseLocation = UserInputService:GetMouseLocation()
local MouseRay = Camera:ViewportPointToRay(MouseLocation.X, MouseLocation.Y)

local Params = RaycastParams.new()
Params.IgnoreWater = true
local Direction = MouseRay.Direction * MaxDistance 
local Origin = MouseRay.Origin
local Raycast = game:GetService("Workspace"):Raycast(Origin, Direction, Params)

if Raycast ~= nil then
      local Part = Instance.new("Part")
      Part.Anchored = true
      Part.Position = Raycast.Position
      Part.Parent = game:GetService("Workspace")

If the RaycastResult is nil then you can assume that it’s out of range. You can use a ternary operator to swap between RaycastResult position and the goal position of the Raycast (the max distance)

part.Position = if Raycast then Raycast.Position else Origin + Direction


This is super redundant. Just use the workspace global.

1 Like

Raycast and Raycast.Position or Origin + Direction

Whichever idiom floats your boat.

Thank you!
I will use the workspace global.