How to make a laser sight?

I’m trying to make a laser sight that reacts to its surrounding, i.e the closer you get to your target, the short the laser becomes. How do I go about this?
Also, I have an issue along with it, when I toggle the laser, this happens:
image

local input = game:GetService("UserInputService")
local laserHolder = script.Parent:WaitForChild("LaserPart")
local character = game.Players.LocalPlayer.Character
local toggled = false 

input.InputEnded:Connect(function(userInput, proc)
	if userInput.UserInputType == Enum.UserInputType.Keyboard then
		if userInput.KeyCode == Enum.KeyCode.F and not toggled then
			toggled = true
			local lookDirection = laserHolder.CFrame.RightVector
			local origin = laserHolder.Position
			local ray = Ray.new(origin, lookDirection * 500) -- studs
			local hitPart, hitPosition = workspace:FindPartOnRay(ray, character)
			local distance = (laserHolder.Position - hitPosition).Magnitude
			laserHolder.Transparency = 0.6
			laserHolder.Size = Vector3.new(distance, 0.05, 0.05)
			laserHolder.CFrame = CFrame.new(laserHolder.CFrame.Position, hitPosition) * CFrame.new(0, 0, -distance / 2)
			if hitPart then
				print("Hit part: " .. hitPart:GetFullName())
			else
				print("Did not hit part")
			end
		elseif userInput.KeyCode == Enum.KeyCode.F and toggled then
			toggled = false
			laserHolder.Transparency = 1
		end
	end
end)

Looks to me like you’re only creating the laser when you click F.
You need to have a function that fires when the player or target moves so the laser can react to that change.

Yes, how do I solve the issue with the CFrame laser going behind me?

Remember that when you set the Position (including CFrame) of a part it’s setting the center of the part to your desired value. That’s why the laser goes behind and in front of you, because the center of it is being set. You want it to be in front, so just offset the CFrame by a couple of studs by doing this

CFrame = CFrame * CFrame.new(offset value, offset value, offset value)

1 Like