Basic flashlight toggle tween to CurrentCamera CFrame

I made the following script to toggle on/off a flashlight with sounds for it, as well as a tween to smoothly transition the brightness from 0 and 1. Is there anything I can improve on, or if there is something that can be optimized?

local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TweenService = game:GetService("TweenService")
local Camera = workspace.CurrentCamera
local Flashlight = ReplicatedStorage.Flashlight:Clone()
local SoundOn = game.Workspace.Sounds.Flashlight.On
local SoundOff = game.Workspace.Sounds.Flashlight.Off
local Mouse = game.Players.LocalPlayer:GetMouse()
local TI = TweenInfo.new(0.2, Enum.EasingStyle.Sine)
Flashlight.Parent = script.Parent

UserInputService.InputBegan:Connect(function(Key)
	if Key.KeyCode == Enum.KeyCode.F then
		if Flashlight:GetAttribute("Toggle") then
			Flashlight:SetAttribute("Toggle", not Flashlight:GetAttribute("Toggle"))
			SoundOff:Play()
		else
			Flashlight:SetAttribute("Toggle", not Flashlight:GetAttribute("Toggle"))
			SoundOn:Play()
		end
	end
end)

RunService.RenderStepped:Connect(function()
	Flashlight.Position = Camera.CFrame.Position
	TweenService:Create(Flashlight, TI, {CFrame = CFrame.lookAt(Flashlight.Position, Mouse.Hit.Position)}):Play()
	TweenService:Create(Flashlight.Light, TI, {Brightness = Flashlight:GetAttribute("Toggle") and 1 or 0}):Play()
end)
3 Likes

I wouldnt recommend using RunService then tweening every 0.2. Since the default fps cap is 60, your going to have 60 tweens running a second, all overlapping eachother.

I would recommend making an attachment in the player hrp with a light looking forward, then tweening the brightness of the light after the sounds play.

3 Likes

Thanks dude, I’ll thinker around with your suggestion and see if I can manage it.

1 Like

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