Laser sight that constantly updates without looking choppy?

What’s happening:
https://docs.google.com/document/d/1i7oxtt_Dl_GMt17w0miqTLisSpIsf-620bLHZuNqxys/edit?usp=sharing

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

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
			while toggled do
                wait()
				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 beam = Instance.new("Part", workspace)
				beam.Anchored = true
				beam.CanCollide = false
				beam.Transparency = 0.6
				beam.BrickColor = BrickColor.new("Really red")
				beam.Material = Enum.Material.Neon
				local distance = (script.Parent.LaserPart.CFrame.Position - hitPosition).magnitude
				beam.Size = Vector3.new(0.05, 0.05, distance)
				beam.CFrame = CFrame.new(script.Parent.LaserPart.CFrame.Position, hitPosition) * CFrame.new(0, 0, -distance / 2)
				game.Debris:AddItem(beam, 0.01)
			end
		elseif userInput.KeyCode == Enum.KeyCode.F and toggled then
			toggled = false
			laserHolder.Transparency = 1
		end
	end
end)

That’s your problem. wait() SUCKS, don’t use it if possible.
Even more, don’t ever do a while wait do loop. They run slow and can cause game lag.

wait() does not run every frame. Use RenderStepped instead.

or tick(), because that works also

2 Likes

While it is better to not use wait(), you’re causing more lag by running stuff faster. Wait() slows down if there’s alot in the task scheduler, it’s a means of anti-lag. (it makes the game appear slow, but improves performance)

Run at Heartbeat or RenderStepped.

Also for the sake of efficiency, I suggest you use a beam and move the 2nd attachment depending on where the ray ended, this way you only have to move the attachment and the beam automatically moves.

1 Like

For what he is trying to achieve though, it’s required something other than wait() is used to match framerate.

1 Like

Yeah, i know, i’m just clearing up a misconception though, It’s good to have correct information.

1 Like