Help with a Laser

Hello,

I am currently coding a laser and it’s going pretty well, but when the laser is pointing in the sky, it doesn’t work correctly. What I mean:

And this is my code

		local barrel = viewModel:FindFirstChild("Barrel",true)
		local shootPart = barrel:FindFirstChild("Shoot")
		local laserLight = laser:FindFirstChild("LaserLight")
		local startAttachment = laserLight:FindFirstChild("Start")
		local endAttachment = laserLight:FindFirstChild("End")
		while wait() do
			if not Modules.IsEquipped then break end
			endAttachment.Visible = laserEnabled
			if laserEnabled then
				local raycastParams = RaycastParams.new()
				raycastParams.FilterDescendantsInstances = {character,viewModel}
				raycastParams.IgnoreWater = true
				raycastParams.FilterType = Enum.RaycastFilterType.Exclude
				local direction = shootPart.CFrame.LookVector
				local range = config.Range and config.Range or 100
				local result = workspace:Raycast(shootPart.Position,direction*range,raycastParams)
				if result and result.Position then
					endAttachment.WorldPosition = result.Position
				end
			else
				endAttachment.WorldPosition = startAttachment.WorldPosition
			end
		end

So how can I fix this? Thanks!

1 Like

I am guessing you are manually turning the laser on and off in the video.

The reason this is happening is because you don’t check if the Raycast doesn’t hit anything at all. When turning it off, this line endAttachment.WorldPosition = startAttachment.WorldPosition will set it’s position of endAttachment to startAttachment, and because the Raycast doesn’t hit anywhere, it won’t update again. Try replacing this code:

if result and result.Position then
	endAttachment.WorldPosition = result.Position
end

with this:

endAttachment.WorldPosition = result and result.Position or (shootPart.Position + direction * range)
1 Like

Works like a charm, thank you very much!

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