How would i make so the nearby parts to a player become gradually transparent the closer

So ive searching everywere for this and i cant find the answer. ive been working on a xray vision googles and i want to make so the nearby parts to a player become gradually transparent

and i maked this but how could i make it so it works for every part in the workspace and also not be laggy

local Players = game:GetService("Players") 
local Player = Players.LocalPlayer 

local Part = workspace.Part 
local Offset = 10 

while true do
    local Distance = Player:DistanceFromCharacter(Part.Position) 
    if Distance then 
        Part.Transparency = (-1 + (Distance - Offset) / 10)*-1
    end
    wait()
end

So, the first step. Don’t use every part in workspace. Since this is an affect that is only affecting parts near the player, only parts near the player should be considered. Creating a structure that effectively helps you filter that is annoying, but luckily you can just have roblox do that part for you. By calling GetPartBoundsInRadius() with the humanoid root part as the center, you can consider only parts that have a chance at being in the affected range. This will cut down the amount of work needed by a huge amount.

Now that you have only the near parts, just loop through all of them and apply that function to them. You may also want to keep track of which ones you have affected and make it so that if a part was changed last time, but not this time to restore it’s transparency to it’s original.

I also recommend using something like RunService.Heartbeat() instead of doing a while loop here. This is because you intend to run it at every frame.

3 Likes

Yeah to add to this could also make it 300 studs or something and do 1 - distance/300 for block transparency

2 Likes

Thanks! works like a charm!

here is what i did

i didnt use RunService.Heartbeat() just in case its too laggy


local Players = game:GetService("Players") 
local Player = Players.LocalPlayer 
local Char = script.Parent

local Offset = 10 

while true do
	local parts = workspace:GetPartBoundsInRadius(Char.HumanoidRootPart.Position,100)
	for _,part in pairs(parts) do
		
		if not part.Parent:FindFirstChild("Humanoid") then
			
			local Distance = Player:DistanceFromCharacter(part.Position) 
			if Distance then 
				
				part.Transparency = (-1 + (Distance - Offset) / 10)*-1
			end
		end
	end
	wait()
end

``
2 Likes

You should use RenderStepped instead of heart beat to be more performant, constant spatial queries can be quite taxing on less performant devices.
You should try using RunService.RenderStepped for its better performance, since you will do a spatial query right before a new frame is rendered.

3 Likes

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