Iโm using a lens flare script, and I want to modify it so the lens flare also works with light objects (point light, spotlight, etc.). Is there any way to detect if the player is looking at light, or if there is a way to modify this script so it works with light too? Thanks!
The LocalScript:
local player = game.Players.LocalPlayer
local camera = workspace.CurrentCamera
local gui = script.Parent
local flares = {}
local char
repeat char = player.Character wait(1/30) until char
for i, child in pairs(gui:GetChildren()) do
if child.Name:sub(1, 5) == "flare" then
flares[child] = tonumber(child.Name:match("flare%d+ : (%-?.+)"))
end
end
function project(cam, point)
local dif = cam:pointToObjectSpace(point)
local fov = math.atan(math.rad(camera.FieldOfView))
local z = -dif.z
if z > 0 then
local x = (dif.x / fov / 1.3) / (z + 1) * (gui.AbsoluteSize.y / gui.AbsoluteSize.x)
local y = (dif.y / fov / 1.3) / (z + 1) * -1
return x, y, true
else
return 0, 0, false
end
end
function rayCast(pos, dir, ignore)
return workspace:FindPartOnRayWithIgnoreList(Ray.new(pos, dir), ignore)
end
while wait(1/60) do
local suns = 0
for i = 1, 5 do
local frame = CFrame.new(camera.CoordinateFrame.p, camera.CoordinateFrame.p + game.Lighting:GetSunDirection())
frame = frame * CFrame.Angles(0, 0, i/5 * math.pi*2)
frame = frame * CFrame.Angles(math.rad(5), 0, 0)
if not rayCast(frame.p, frame.lookVector*999, {char}) then
suns = suns + 1
end
end
if suns > 0 then
local x, y, z = project(camera.CoordinateFrame, camera.CoordinateFrame.p + game.Lighting:GetSunDirection()*25)
if z then
for flare, pos in pairs(flares) do
flare.Position = UDim2.new(0.5 + x*pos, -flare.AbsoluteSize.x/2, 0.5 + y*pos, -flare.AbsoluteSize.y/2)
flare.Visible = true
end
else
for flare in pairs(flares) do
flare.Visible = false
end
end
else
for flare, pos in pairs(flares) do
flare.Visible = false
end
end
end
Sorry, this doesnโt really answer my question. I want to know if there is a way to detect if the player is looking at a light source, not touching it. Thanks!
I believe that @LOG1CEXE was suggesting the use of an invisible part that acts as a โhitboxโ for the light. You can detect when the player enters the light when the player touches the invisible part. You could also try using raycasts to detect when a player looks at a part that has a light source, but avoid doing that every frame due to performance costs.
Your solution definitely resides with raycasting. The general idea is to cast a ray from the cameraโs position to the light source, and if thereโs nothing intersecting then display the lens flare. Otherwise, disable it. Youโll also want to take field of view into account. For performance, you could probably run this process on the Heartbeat event of RunService.