Combining transparencies for lens flare

I’m making a lens flare with a image label

I’m trying to combine transparencies to decide how the final image label looks, right now it will only detect the first part in the way so if there’s a semi-transparent part in front of an opaque part the lens flare will still shine through.

I assume I’ll have to do this using raycasts but I’m not entirely sure how I’d go about detecting multiple objects.

--!nocheck

-- Services --

local TweenService:TweenService = game:GetService('TweenService')

-- Player --

local CurrentCamera:Camera = workspace.CurrentCamera

-- GUI --

local LensFlare:ImageLabel = game.Players.LocalPlayer.PlayerGui:WaitForChild('LensFlareGUI'):WaitForChild('LensFlare')

-- Variables --

local Transparencies:number = 0

-- Functions --

local function UpdateLensFlare()
	
	local SunDirection:Vector3 = game.Lighting:GetSunDirection()*1000
	
	local FacingSun:Vector3 = SunDirection.Unit:Dot(CurrentCamera.CFrame.LookVector)
	local SunPosition:Vector3 = CurrentCamera:WorldToScreenPoint(SunDirection)
	LensFlare.Position = UDim2.fromScale(SunPosition.X/CurrentCamera.ViewportSize.X,SunPosition.Y/CurrentCamera.ViewportSize.Y)
	local RaycastResult:RaycastResult = workspace:Raycast(CurrentCamera.CFrame.Position,SunDirection) or {Position = CurrentCamera.CFrame.Position+SunDirection}
	
	if FacingSun > 0 then
	
		if RaycastResult.Instance then
		
			Transparencies = 1-((1-RaycastResult.Instance.Transparency)*(1-RaycastResult.Instance.LocalTransparencyModifier))
	
			if Transparencies == 0 then
	
				TweenService:Create(LensFlare,TweenInfo.new(),{ImageTransparency = 1}):Play()
			
			end	
		
		else
			
			Transparencies = 1
		
		end	
		TweenService:Create(LensFlare,TweenInfo.new(),{ImageTransparency = math.clamp((-FacingSun+1),0,1)+(1-Transparencies)}):Play()
		
	else
		
		LensFlare.ImageTransparency = 1
		
	end
end

-- Connections --

CurrentCamera:GetPropertyChangedSignal('CFrame'):Connect(UpdateLensFlare)

-- Return --

return LensFlare
1 Like