Increase fog as player gets closer

I’m trying to increase a density when player is getting closer using position, it works but is there a better approach?

local IsTouching = false
task.spawn(function()
	for _,v in Character:GetChildren() do
		v.Touched:Connect(function(Hit)
			if tostring(Hit):lower():match("triggerfog") then
				IsTouching = true
			end
		end)
		v.TouchEnded:Connect(function(Hit)
			if tostring(Hit):lower():match("triggerfog") then
				IsTouching = false
			end
		end)
		while true do
			task.wait()
			if IsTouching then
				TweenService:Create(game:GetService("Lighting").Atmosphere, TweenInfo.new(0.2), {Density = math.abs((Character.PrimaryPart.Position - workspace.Folder.Union.Position).Magnitude) / 40}):Play()
			end
		end
	end
end)

Highlighted parts are what’s suppose to increase the density.
(Middle is just what sets the boolean, like the player is inside an area)

2 Likes

If you want to use position, you can use this loop. There is no need for touching parts, but if there was, you could use GetTouchingParts.

local positionToGetCloseTo : Vector3 = Vector3.zero
local atmosphere = game:GetService("Lighting").Atmosphere
game:GetService("RunService").Heartbeat:Connect(function(delta)
	local dist = (Character.PrimaryPart.Position - workspace.Folder.Union.Position).Magnitude -- This is always positive. (thats what magnitude is)
	atmosphere.Density = dist / 40
end)
2 Likes

Is there a way to do this for part’s transparency? decrease transparency as player gets close?
also for math abs i did that beacuse my first attempt made the density becmoe negative (-30 or below)