How do I fix welded parts moving when scaling part?

I made a scale tool in my building game but whenever you scale a unanchored part it moves the attached parts. I know this is how weldconstraints are intended to be but I dont want to use normal weld because I heard that can lag.

I tried disabling and renabling the welds, I also tried deleting the welds and re-adding them but both of those solutions didnt work.

Server Side Scale Function:

function placement.Scale(player, part, cframe, size)
	local playerTeam = player.Team
	if not playerTeam then return false end

	local playerPlot = plotsFolder:FindFirstChild(playerTeam.Name)
	if not playerPlot then return false end

	local userFolder = placedBlocksFolder:FindFirstChild(player.UserId)
	if not userFolder then return false end

	if not part or not part.Parent then return false end
	local block = part.Parent
	if block.Parent ~= userFolder then return false end
	if not CollectionService:HasTag(block, "Scalable") then return false end

	local blockId = block:GetAttribute("BLOCKID")
	if not blockId then return false end

	local inventory = InventoryModule.getPlayerInventory(player)
	local index = findItemIndex(inventory, blockId)

	local validateAmount
	if placement.PlacementInventory[player.UserId] then
		validateAmount = InventoryModule.ValidatePlayerBlockAmount(player, blockId, placement.PlacementInventory[player.UserId][blockId])
	else
		validateAmount = InventoryModule.ValidatePlayerBlockAmount(player, blockId, inventory[index] and inventory[index].AMOUNT or 0)
	end
	if not validateAmount then return false end

	local gamePassFolder = player:FindFirstChild("Gamepasses")
	if not gamePassFolder then return false end
	local gamepassValue = gamePassFolder:FindFirstChild("Extended_Plot")
	if not gamepassValue then return false end

	local normalBounds = playerPlot:FindFirstChild("FreeBuildBounds")
	local paidBounds = playerPlot:FindFirstChild("PaidBuildBounds")
	if not normalBounds or not paidBounds then return false end

	local partsInBounds = getBlockInBounds.IsPivotInBounds(cframe, normalBounds)
	local partsInPaidBounds = getBlockInBounds.IsPivotInBounds(cframe, paidBounds)
	local validatedBounds = validateBounds(partsInPaidBounds, partsInBounds, gamepassValue)
	if not validatedBounds then return false end

	local prevSize = part.Size
	local prevCFrame = part.CFrame
	local anchor = part.Anchored

	-- Store and remove all welds referencing this block
	local removedWelds = {}
	for _, weld in ipairs(part:GetChildren()) do
		if weld:IsA("WeldConstraint") then
			table.insert(removedWelds, {Part0 = weld.Part0, Part1 = weld.Part1})
			weld:Destroy()
		end
	end

	part.Anchored = true
	part.Size = size
	part.CFrame = cframe

	local totalAmount = getAllScaledAmount(block, userFolder)
	local currentAmount = 0
	if index then
		currentAmount = inventory[index].AMOUNT or 0
	end
	if currentAmount - totalAmount <= 0 then
		part.Size = prevSize
		part.CFrame = prevCFrame
		part.Anchored = anchor
		-- Restore welds if scaling fails
		for _, weldData in ipairs(removedWelds) do
			local newWeld = Instance.new("WeldConstraint")
			newWeld.Part0 = weldData.Part0
			newWeld.Part1 = weldData.Part1
			newWeld.Parent = weldData.Part0
		end
		return false
	end

	part.Anchored = anchor

	-- Recreate the welds after scaling
	for _, weldData in ipairs(removedWelds) do
		local newWeld = Instance.new("WeldConstraint")
		newWeld.Part0 = weldData.Part0
		newWeld.Part1 = weldData.Part1
		newWeld.Parent = weldData.Part0
	end

	placement.PlacementInventory[player.UserId][blockId] = currentAmount - totalAmount
	ReplicatedStorage.Remotes.UpdateInventorySlots:FireClient(player, blockId, placement.PlacementInventory[player.UserId][blockId])

	placement.CachedBlockProperties[block] = placement.CachedBlockProperties[block] or {}
	placement.CachedBlockProperties[block].Size = part.Size

	return true
end

Welding Module:

local SurfaceWeldModule = {}

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

local DEBUG = true
local Offset = 0.05
local OffsetVector = Vector3.new(Offset, Offset, Offset)

local Params = OverlapParams.new()
Params.FilterType = Enum.RaycastFilterType.Exclude

local WeldCache = setmetatable({}, { __mode = "k" })

local function DebugPrint(...)
	if DEBUG then
		print("[SurfaceWeldModule]:", ...)
	end
end

local function IsDescendantOfCharacter(part)
	local ancestor = part
	while ancestor and ancestor.Parent do
		if ancestor:IsA("Model") and Players:GetPlayerFromCharacter(ancestor) then
			return true
		end
		ancestor = ancestor.Parent
	end
	return false
end

local function InSameModel(partA, partB)
	local rootA = partA:FindFirstAncestorOfClass("Model")
	local rootB = partB:FindFirstAncestorOfClass("Model")
	return rootA and rootA == rootB
end

local function CacheKeyExists(partA, partB)
	local cacheA = WeldCache[partA]
	local cacheB = WeldCache[partB]
	return (cacheA and cacheA[partB]) or (cacheB and cacheB[partA])
end

local function CacheKeyAdd(partA, partB)
	WeldCache[partA] = WeldCache[partA] or setmetatable({}, { __mode = "k" })
	WeldCache[partA][partB] = true
	WeldCache[partB] = WeldCache[partB] or setmetatable({}, { __mode = "k" })
	WeldCache[partB][partA] = true
end

local function CheckIfCanWeld(partA, partB)
	if partA == partB then return false end
	print("is both")
	if CacheKeyExists(partA, partB) then return false end
	print("key exists")
	if InSameModel(partA, partB) then return false end
	print("is in same model")

	for _, weld in ipairs(partB:GetChildren()) do
		print("checking", weld)
		if weld:IsA("WeldConstraint") then
			print("found weld", weld)
			if (weld.Part0 == partA and weld.Part1 == partB) or (weld.Part0 == partB and weld.Part1 == partA) then
				print("returining false")
				CacheKeyAdd(partA, partB)
				return false
			end
		end
	end

	return true
end

local weldCount = 0 

local ModelWeldCache = setmetatable({}, { __mode = "k" })

local function CreateWeld(partA, partB)
	if IsDescendantOfCharacter(partA) or IsDescendantOfCharacter(partB) then
		DebugPrint("Skipped welding character part:", partA.Name, partB.Name)
		return
	end
	
	if CollectionService:HasTag(partA, "BlockWelds") or CollectionService:HasTag(partB, "BlockWelds") then
		DebugPrint("Skipped welding parts because one of the parts had the 'BlockWelds' tag. (", partA.Name, partB.Name..")")
		return
	end

	local modelA = partA:FindFirstAncestorOfClass("Model")
	local modelB = partB:FindFirstAncestorOfClass("Model")

	if modelA and modelB then
		if modelA == modelB then return end

		ModelWeldCache[modelA] = ModelWeldCache[modelA] or setmetatable({}, { __mode = "k" })
		if ModelWeldCache[modelA][modelB] then return end

		ModelWeldCache[modelA][modelB] = true
		ModelWeldCache[modelB] = ModelWeldCache[modelB] or setmetatable({}, { __mode = "k" })
		ModelWeldCache[modelB][modelA] = true

		local weldA = modelA.PrimaryPart or partA
		local weldB = modelB.PrimaryPart or partB

		local weld = Instance.new("WeldConstraint")
		weld.Part0 = weldA
		weld.Part1 = weldB
		weld.Parent = weldA

		CacheKeyAdd(weldA, weldB)
		weldCount += 1
		DebugPrint("Welded model:", modelA.Name, "<->", modelB.Name)
	else
		if CheckIfCanWeld(partA, partB) then
			local weld = Instance.new("WeldConstraint")
			weld.Part0 = partA
			weld.Part1 = partB
			weld.Parent = partA
			CacheKeyAdd(partA, partB)
			weldCount += 1
			DebugPrint("Welded parts:", partA.Name, "<->", partB.Name)
		end
	end
end

local function SurfaceWeldPart(part)
	if not part:IsA("BasePart") then return end

	Params.FilterDescendantsInstances = { part }

	local partsNearby = workspace:GetPartBoundsInBox(part.CFrame, part.Size + OffsetVector, Params)

	local connectedModels = {}

	for _, nearbyPart in ipairs(partsNearby) do
		if nearbyPart:IsA("BasePart") and CheckIfCanWeld(part, nearbyPart) then
			local modelA = part:FindFirstAncestorOfClass("Model") or part
			local modelB = nearbyPart:FindFirstAncestorOfClass("Model") or nearbyPart

			if not connectedModels[modelB] then
				CreateWeld(part, nearbyPart)
				connectedModels[modelB] = true
			end
		end
	end
end


function SurfaceWeldModule.WeldPart(part)
	SurfaceWeldPart(part)
end

function SurfaceWeldModule.WeldModel(model)
	for _, part in ipairs(model:GetDescendants()) do
		SurfaceWeldPart(part)
	end
end

function SurfaceWeldModule.WeldParts(partsArray)
	for _, part in ipairs(partsArray) do
		SurfaceWeldPart(part)
	end
end

function SurfaceWeldModule.ClearCacheForPart(part)
	if WeldCache[part] then
		for otherPart, _ in pairs(WeldCache[part]) do
			if WeldCache[otherPart] then
				WeldCache[otherPart][part] = nil
			end
		end
		WeldCache[part] = nil
	end
end

function SurfaceWeldModule.ClearWelds(target)
	local parts = {}

	if typeof(target) == "Instance" then
		parts = target:GetDescendants()
	elseif typeof(target) == "table" then
		parts = target
	end

	for _, part in ipairs(parts) do
		if part:IsA("BasePart") then
			for _, child in ipairs(part:GetChildren()) do
				if child:IsA("WeldConstraint") then
					child:Destroy()
					DebugPrint("Destroyed weld on:", part.Name)
				end
			end
		end
	end
end

function SurfaceWeldModule.PruneWeldCache()
	for partA, map in pairs(WeldCache) do
		if not partA:IsDescendantOf(workspace) then
			WeldCache[partA] = nil
		else
			for partB, _ in pairs(map) do
				if not partB:IsDescendantOf(workspace) then
					map[partB] = nil
				end
			end
		end
	end
end

function SurfaceWeldModule.CleanDanglingWeldsIncremental(root, chunkSize)
	root = root or workspace
	chunkSize = chunkSize or 50

	local welds = {}
	for _, weld in ipairs(root:GetDescendants()) do
		if weld:IsA("WeldConstraint") or weld:IsA("Weld") or weld:IsA("Motor6D") then
			table.insert(welds, weld)
		end
	end

	local index = 1
	local total = #welds

	local RunService = game:GetService("RunService")
	local conn
	conn = RunService.Heartbeat:Connect(function()
		for i = 1, chunkSize do
			if index > total then
				conn:Disconnect()
				return
			end

			local weld = welds[index]
			if not weld.Part0 or not weld.Part0.Parent or not weld.Part1 or not weld.Part1.Parent then
				print(weld)
				weld:Destroy()
			end
			index += 1
		end
	end)
end

function SurfaceWeldModule.RemoveWeldsInvolvingFolderParts(blocks, folder)
	if not folder or not folder:IsA("Folder") then
		warn("[SurfaceWeldModule]: Invalid folder passed to RemoveWeldsInvolvingFolderParts")
		return
	end

	local partsSet = {}
	for _, part in ipairs(folder:GetDescendants()) do
		if part:IsA("BasePart") then
			partsSet[part] = true
		end
	end

	local weldsRemoved = 0
	
	for _, model in ipairs(blocks) do
		if model:IsA("Model") then
			for _, descendant in ipairs(model:GetDescendants()) do
				if descendant:IsA("WeldConstraint") then
					local part0 = descendant.Part0
					local part1 = descendant.Part1
					if (part0 and partsSet[part0]) or (part1 and partsSet[part1]) then
						descendant:Destroy()
						weldsRemoved += 1
						DebugPrint("Destroyed weld involving folder part:", descendant.Name)
					end
				end
			end
		end
	end

	DebugPrint("Removed", weldsRemoved, "welds involving parts from", folder.Name)
end


function SurfaceWeldModule.ClearCache()
	table.clear(WeldCache)
	DebugPrint("Cleared WeldCache")
end

function SurfaceWeldModule.SetDebug(state)
	DEBUG = state
end

return SurfaceWeldModule

here

local partbanchor = partb.Anchored;
partb.Anchored=true;
weld:Destroy();
scale(parta);
weld = Instance.new('WeldConstraint');
weld.Part0 = parta;
weld.Part1 = partb;
weld.Parent = parta;
partb.Anchored = partbanchor;

I already tried doing that it didnt work

try using welds instead

I heard that can cause more lag than weld constraints, not sure though

I used welds, they won’t lag

Alr, I modified my weld module to use welds instead but it sometimes works and sometimes doesnt.

try using the CFrame0/CFrame1 accessors/properties

This is how im welding it (after scaling)

local connectedWelds = {}
	for _, w in ipairs(part:GetChildren()) do
		if w:IsA("Weld") then
			table.insert(connectedWelds, {weld = w, part0 = w.Part0, part1 = w.Part1, c0 = w.C0, c1 = w.C1})
			w:Destroy()
		end
	end

	part.Size = newSize
	part.CFrame = newCFrame

	for _, data in ipairs(connectedWelds) do
		local w = Instance.new("Weld")
		w.Part0 = data.part0
		w.Part1 = data.part1
		w.C0 = data.part0.CFrame:ToObjectSpace(data.part1.CFrame)
		w.C1 = CFrame.new()
		w.Parent = data.part0
	end

change the already existing welds, and remove the invalid ones

How would I do that? Modify the weld module or the scale function?

get the welds and update their cframe properties( modify the part that destroies the welds)

Like this?

part.Anchored = true
	
	local welds = {}

	for _, weld in pairs(part:GetChildren()) do
		if weld:IsA("Weld") and weld.Part0 and weld.Part1 then
			welds[weld] = {C0 = weld.C0, C1 = weld.C1, Part0 = weld.Part0, Part1 = weld.Part1}
		end
	end

	part.Size = newSize
	part.CFrame = newCFrame

	for weld, data in pairs(welds) do
		local offset = data.Part0.CFrame:ToObjectSpace(data.Part1.CFrame)
		weld.C0 = data.C0
		weld.C1 = data.C1
		data.Part1.CFrame = data.Part0.CFrame * data.C0 * data.C1:Inverse() * offset
	end
	part.Anchored = anchorState

yes

Alr I tested it and it made no difference. (The part thats not being scaled teleports to the center)

when setting the position, fix the welds by transforming C0/C1 by the delta thats used for moving the scaled part

Making some progress. Still really buggy tho

local deltaCFrame = prevCFrame:ToObjectSpace(newCFrame)

	local weldsData = {}
	for _, w in pairs(part:GetChildren()) do
		if w:IsA("Weld") and w.Part0 and w.Part1 then
			weldsData[w] = {C0 = w.C0, C1 = w.C1, Part0 = w.Part0, Part1 = w.Part1}
		end
	end

	part.Size = newSize
	part.CFrame = newCFrame

	for weld, data in pairs(weldsData) do
		if data.Part0 and data.Part1 then
			weld.C0 = deltaCFrame * data.C0
		end
	end

	part.Anchored = anchorState

do it before the physics step

It scales properly after the first scale only when its on the same axis