Hey dev’s! I’m trying to make a horror game. And i want a flashlight that follows the players mouse [That is not a tool]. I just placed an attachment inside the character and added a spotlight. Please someone help me.
local RS = game:GetService(“RunService”)
local player = game.Players.LocalPlayer
local Mouse = player:GetMouse()
local character = player.Character or player.CharacterAdded:Wait()
while wait() do
local x, y, z = Mouse.Hit:ToEulerAnglesXYZ()
local Flashlight = character:WaitForChild("HumanoidRootPart"):WaitForChild("FlashlightAttachment")
print(Mouse.Hit.y)
Flashlight.CFrame = CFrame.Angles(0, math.rad(Mouse.Hit.y), 0)
I wouldn’t recommend rotating attachments, so try this instead:
local plr = game.Players.LocalPlayer;
local mouse = plr:GetMouse();
while wait() do
LIGHT.CFrame = CFrame.lookAt(LIGHT.Position, mouse.Hit.Position); -- LIGHT is the headlight
end
That same documentation also has an example which is similar to what you're looking for.. of course you'd have to adapt it.
Mouse.Hit Laser Beam
The code in this sample, when placed inside a LocalScript within StarterPlayerScripts will draw a red laser beam between the character’s head and Mouse.Hit at all times.
Note, this beam will pass directly through obstructions in third person as the Mouse ’s raycasting is done from the Workspace.CurrentCamera not the head.
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- grab local player
local localPlayer = Players.LocalPlayer
-- create beam
local beam = Instance.new("Beam")
beam.Segments = 1
beam.Width0 = 0.2
beam.Width1 = 0.2
beam.Color = ColorSequence.new(Color3.new(1, 0, 0))
beam.FaceCamera = true
-- create attachments
local attachment0 = Instance.new("Attachment")
local attachment1 = Instance.new("Attachment")
beam.Attachment0 = attachment0
beam.Attachment1 = attachment1
-- parent attachments to Terrain
beam.Parent = workspace.Terrain
attachment0.Parent = workspace.Terrain
attachment1.Parent = workspace.Terrain
-- grab the mouse
local mouse = localPlayer:GetMouse()
-- connect to RenderStepped (update every frame)
RunService.RenderStepped:Connect(function()
-- make sure the character exists
local character = localPlayer.Character
if not character then
-- disable the beam
beam.Enabled = false
return
end
-- make sure the head exists
local head = character:FindFirstChild("Head")
if not head then
-- disable the beam
beam.Enabled = false
return
end
-- enable the beam
beam.Enabled = true
-- define origin and finish
local origin = head.Position
local finish = mouse.Hit.p
-- move the attachments
attachment0.Position = origin
attachment1.Position = finish
end)