Code that changes object size depending on how far the player/camera is located from the object (locally)

Hello. I would like write a code with this concept: an object size changes depending on how far the player/camera is located from the object

I inserted a localscript inside of the object in workspace and i pasted this code suggested by AI:

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local player = Players.LocalPlayer
local part = script.Parent

-- Change these numbers to fit your game
local minDistance = 5   -- Closest distance for max size
local maxDistance = 30  -- Farthest distance for normal size
local minSize = Vector3.new(1, 1, 1)   -- Size when far away
local maxSize = Vector3.new(5, 5, 5)   -- Size when close

RunService.RenderStepped:Connect(function()
	local character = player.Character
	if not character or not character:FindFirstChild("HumanoidRootPart") then return end
	
	local rootPart = character.HumanoidRootPart
	local distance = (rootPart.Position - part.Position).Magnitude
	
	-- Calculate alpha based on distance (0 at maxDistance, 1 at minDistance)
	local alpha = math.clamp(1 - ((distance - minDistance) / (maxDistance - minDistance)), 0, 1)
	
	-- Lerp (blend) between the min and max size
	part.Size = minSize:Lerp(maxSize, alpha)
end)

But it does not work! I tried even simpler code, like this:

script.Parent.Size = vector3.new(50, 50, 50)

But it does not work! Where did I go wrong? :sob:

LocalScripts do not run in workspace. You can instead use a Script with RunContext set to Client or do this from some other location (like StarterCharacterScripts)

1 Like

l think this code must calls in StarterGui or StarterPlayerScripts and also l think it code need for hide problems with NearZPlane? camera when object far away a camera but camera cut clipping this part in 95 km away

1 Like

in such cases you might want to set a breakpoint to the place you are interested in.
or add some print("Hello world!")
so you will get a hint if the code works at all.

I checked this code and he is working, just is local script must put in StarterGui

I even tried to print the result, but did not work!

As others have said, it works but you need to make it a ‘script’ with run context set to client