Raycast is buggy HELP!

Hey there. FYI, ive never worked with Raycasts before so this is a first LoL. Anyways, I’ve created a raycast that will show a beam to where the player VR hand is pointing. Problem is its really buggy. And what I mean by that is its all over the place. I have no idea what I’m doing wrong or what to fix so please help.


CODE:

game:GetService("RunService").RenderStepped:Connect(function()
	local rayOrigin = vrCharacter["RightController"].Position
	local rayDirection = vrCharacter["RightController"].CFrame.LookVector*10
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {character, vrCharacter}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)

	if (raycastResult) then
		local hitPart = raycastResult.Instance
		print(hitPart.Name)
		local dist = (rayDirection - rayOrigin).magnitude
		laser.CFrame = CFrame.new(rayOrigin, raycastResult.Position) * CFrame.new(0, 0, -dist/2)
		laser.Size = Vector3.new(0.25, 0.25, dist)
		laser.Transparency = 0
	else
		laser.Transparency = 1
	end
end)
1 Like

I wouldn’t hide the laser just because you didn’t hit a part.

game:GetService("RunService").RenderStepped:Connect(function()
	local rayOrigin = vrCharacter["RightController"].Position
	local rayDirection = vrCharacter["RightController"].CFrame.LookVector*10
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {character, vrCharacter}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)

	if (raycastResult) then
		local hitPart = raycastResult.Instance
		print(hitPart.Name)
		local dist = (rayDirection - rayOrigin).magnitude
		laser.CFrame = CFrame.new(rayOrigin, raycastResult.Position) * CFrame.new(0, 0, -dist/2)
		laser.Size = Vector3.new(0.25, 0.25, dist)
		laser.Transparency = 0
	else
		local dist = (rayDirection - rayOrigin).magnitude
		laser.CFrame = CFrame.new(rayOrigin, rayOrigin + rayDirection) * CFrame.new(0, 0, -dist/2)
		--origin + direction is the position you're raycasting towards. 
		laser.Size = Vector3.new(0.25, 0.25, dist)
		laser.Transparency = 0
	end
end)

turns out I just forgot to add the laser to one of the blacklisted items. :man_facepalming:

1 Like

I do still have a problem though, the beam still goes longer then needed:

Because your dist variable uses (origin - direction) rather than (origin - resultPosition)

local dist = (rayDirection - rayOrigin).magnitude

should be

local dist = (raycastResult.Position - rayOrigin).magnitude
1 Like

Thanks man LOL. It works right now.

1 Like