How to show raycast beam regardless if it returns a result

i have this code here (supposed to visualize the raycast)

local rayOrigin = hrp.Position
	local rayDirection = hrp.CFrame.lookVector * 1000

	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Exclude
	raycastParams.FilterDescendantsInstances = {char}
	raycastParams.IgnoreWater = true
	
	local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
	
	local function dobeam()
		local distance = (rayOrigin - raycastResult.Position).Magnitude
		local part = Instance.new("Part", workspace)
		part.Anchored = true
		part.CanCollide = false
		part.Size = Vector3.new(0.1,0.1,distance)
		part.CFrame = CFrame.lookAt(rayOrigin, rayDirection)*CFrame.new(0, 0, -rayDirection/2)
	end

problem is i want it to be visualized regardless if it hits a part or not

(also when it visualizes the part ends in teh middle of the raycast)

1 Like

You have to check if there’s a RaycastResult and set the distance variable accordingly, if there is no RaycastResult, the distance will just be the length of rayDirection

so:

local distance
if RaycastResult ~= nil then
    distance = (rayOrigin - raycastResult.Position).Magnitude
else
    distance = rayDirection.Magnitude
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.