Optimize lerping of models on client

I am working on a game in which you drive with carts on a track from node to node. On the server, the player positions are stored as simple parts that are updated every frame. On the client, my code goes through all active players and lerps their carts to the correct position. Sometimes I get minor stuttering on mobile, and with the microprofiler I noticed that its the lerping function which i gave the name of ‘lerping’. The function is bound to bindtorenderstep like this: runService:BindToRenderStep('animationLoop',Enum.RenderPriority.Camera.Value-1,syncLoop)

This is the full function:

function syncLoop(delta)
	deltaCount += delta
	debug.profilebegin('AnimCarts')
	for _,folder in ipairs(animatePlrsList) do
		local cart
		local s,e = pcall(function()
			cart = folder.Cart :: Model
		end)
		if not s then continue end
		
		debug.profilebegin('cartPos')
		local posPart = folder:WaitForChild('CartPosition') :: BasePart
		local lerpSpeed = 9 -- Lower is smoother, but lags behind the actual position
		
		local lerpAlpha = math.clamp(delta * lerpSpeed, 0, 1)
		local currentPivot = cart:GetPivot()
		local standStill = folder:GetAttribute('stillIntersection')
		
		debug.profilebegin('targetPivot')
		local targetPivot = posPart.CFrame * CFrame.new(0,-posPart.Position.Y + cart:GetAttribute('FloorDistance') + floorHeight,0)
		if folder.Name == ownFolderName and not standStill then
			targetPivot *= CFrame.new(0,0,-2) --makes coyote time
		end
		debug.profileend()
		
		debug.profilebegin('Lerping')
		local lerpedPivot = currentPivot:Lerp(targetPivot, lerpAlpha)
		cart:PivotTo(lerpedPivot)
		debug.profileend()
		debug.profileend()
		
		debug.profilebegin('Wheel')
		local diameter = cart.Wheels:GetAttribute('Diameter')
		local distTraveled = folder:GetAttribute('CurrentSpeed')*delta

		if not standStill then
			for _,wheel in ipairs(cart.Wheels:GetChildren()) do
				local reverser = 1
				local wheelName = wheel.Name
				if string.sub(wheelName,#wheelName) == 'R' then
					reverser = -1
				end
				
				wheel:PivotTo(wheel.WorldPivot * CFrame.Angles(math.rad(distTraveled/diameter * 360 * reverser),0,0))
			end
		end
		debug.profileend()
	end
	debug.profileend()
	
	debug.profilebegin('AnimProjectiles')
	for _,folder in ipairs(animateProjectilesList) do
		local proj = folder.Projectile
		local posPart = folder:WaitForChild('PosPart') :: BasePart
		local lerpSpeed = 15
		
		local lerpAlpha = math.clamp(delta * lerpSpeed, 0, 1)
		local currentPivot = proj:GetPivot()
		local targetPivot = posPart.CFrame * CFrame.new(0,projectileHeight,0)
		local lerpedPivot = currentPivot:Lerp(targetPivot, lerpAlpha)
		proj:PivotTo(lerpedPivot)
	end
	debug.profileend()
	
	local curve = math.sin(tick()*bobSpeed + 0.5)
	
	debug.profilebegin('PowerUpsBob')
	for _,model in ipairs(animatePowerUpList) do
		local basePos = model.WorldPivot.Position
		local pos = Vector3.new(basePos.X,powerUpheight+curve*bobHeight,basePos.Z)
		local rX,rY,rZ = model.WorldPivot:ToOrientation()
		
		model:PivotTo(CFrame.new(pos) * CFrame.Angles(rX,rY+math.rad(-1*delta*60),rZ))
	end
	debug.profileend()
	
	debug.profilebegin('EngineShake')
	if deltaCount > 0.05 and ownCart then
		local offset = ownCart.Engine:GetAttribute('Offset')
		ownCart.Engine:PivotTo(ownCart.EngineAttachment.WorldCFrame * offset:Inverse() * CFrame.new(math.random(-engineShake*100,engineShake*100)/100,math.random(-engineShake*100,engineShake*100)/100,0))
		deltaCount = 0
	end
	debug.profileend()
end

This is the microprofiler tab of the Lerping debug part:

What can I do to reduce the stuttering on mobile? If I remove the lerping, the carts will move jittery.

well i can tell you for sure that lerping is the LEAST of your worries.

:PivotTo isn’t the fastest method out there, but that’s trival compared to everything else you’re doing. you’re handling literally everything, every single frame.
half of the stuff in this program should be moved outside of the function and handled in a different way, and some of it doesn’t even need to be called repeatedly; you absolutely DO NOT need that pcall there, nor would you ever need it in any loop ever (generally), and the same goes for WaitForChild. and you definitely do not want to do string operations in loops bc they are slooooooow.
last but not least, even the stuff that should be running per frame, like lerping the powerups and carts, would fair better outside of RenderStepped. even though they are visual, they don’t require to be rendered along with the camera (much less before it).

there’s a lot of ways you could go about changing the architecture of this but this comment is already long enough. in regards to lerping specifically; assuming your cart models have lots of parts :BulkMoveTo() seems to be faster if i’m not mistaken. but ideally you should let roblox physics handle this for you bc that’s the best option. try welding everything to a singular primary part and then CFraming it or using some body movers if you think that’ll be easier

best of luck : P

I asked roblox assistant for some help too, and i changed it so it caches some stuff so it doesnt need to calculate as much every single time. That way i got rid of the string operations, getting certain attributes and finding the cframe each frame.

As for the pcall, sometimes the player can get shot, and the cart is moved out of the folder into serverstorage, so this is a check whether the cart exists inside the folder.

When would you recommend putting the function if not in renderstepped? My idea was that because its not physics based it can go before physics simulation, and before the camera to make sure everything is in the right position.

this is the updated function:

function syncLoop(delta)
	local currentTime = tick()
	
	debug.profilebegin('AnimCarts')
	for _,folder : Folder in ipairs(animatePlrsList) do
		local cart
		local s,e = pcall(function()
			cart = folder.Cart :: Model
		end)
		if not s then continue end
		
		local cache = cartCache[folder.Name]
		
		if not cache then
			cache = {
				posPart = folder:WaitForChild('CartPosition'):: BasePart,
				floorDistance = cart:GetAttribute('FloorDistance') :: number,
				lastPivot = cart:GetPivot(),
				wheels = {}
			}
			
			if cart == ownCart then
				cache.engineOffset = ownCart.Engine:GetAttribute('Offset')
			end
			
			if cart.Wheels then
				local diameter = cart.Wheels:GetAttribute('Diameter')
				for _,wheel in ipairs(cart.Wheels:GetChildren()) do
					local reverser = string.sub(wheel.Name, #wheel.Name) == 'R' and -1 or 1
					table.insert(cache.wheels, {
						wheel = wheel,
						reverser = reverser,
						diameter = diameter,
						currentRotation = 0
					})
				end
			end
			print('created cache')
			cartCache[folder.Name] = cache
		end
		
		debug.profilebegin('cartPos')
		local lerpAlpha = math.clamp(delta * lerpSpeed, 0, 1)
		local standStill = folder:GetAttribute('stillIntersection')
		
		debug.profilebegin('targetPivot')
		--calculate target pivot
		local targetPivot = cache.posPart.CFrame * CFrame.new(0,-cache.posPart.Position.Y + cache.floorDistance + floorHeight,0)
		if folder.Name == ownFolderName and not standStill then
			targetPivot *= CFrame.new(0,0,-2) --makes coyote time
		end
		debug.profileend()
		
		debug.profilebegin('Lerping')
		--use cached last pivot for lerping
		local lerpedPivot = cache.lastPivot:Lerp(targetPivot, lerpAlpha)
		cart:PivotTo(lerpedPivot)
		cache.lastPivot = lerpedPivot
		debug.profileend()
		debug.profileend()
		
		debug.profilebegin('Wheel')
		if not standStill then
			local distTraveled = folder:GetAttribute('CurrentSpeed') * delta
			local rotAngle = math.rad(distTraveled / cache.wheels[1].diameter * 360)
			
			for _,wheelData in ipairs(cache.wheels) do
				local wheel = wheelData.wheel
				local currentRotation = wheelData.currentRotation
				currentRotation += rotAngle * wheelData.reverser
				wheelData.currentRotation = currentRotation
				
				wheel:PivotTo(wheel.WorldPivot * CFrame.Angles(currentRotation,0,0))
			end
		end
		debug.profileend()
	end
	debug.profileend()
	
	debug.profilebegin('AnimProjectiles')
	for _,folder in ipairs(animateProjectilesList) do
		local proj = folder.Projectile
		local posPart = folder:WaitForChild('PosPart') :: BasePart
		local lerpSpeed = 15
		
		local lerpAlpha = math.clamp(delta * lerpSpeed, 0, 1)
		local currentPivot = proj:GetPivot()
		local targetPivot = posPart.CFrame * CFrame.new(0,projectileHeight,0)
		local lerpedPivot = currentPivot:Lerp(targetPivot, lerpAlpha)
		proj:PivotTo(lerpedPivot)
	end
	debug.profileend()
	
	
	debug.profilebegin('PowerUpsBob')
	local curve = math.sin(currentTime*bobSpeed + 0.5)
	for _,model in ipairs(animatePowerUpList) do
		local basePos = model.WorldPivot.Position
		local pos = Vector3.new(basePos.X,powerUpheight+curve*bobHeight,basePos.Z)
		local rX,rY,rZ = model.WorldPivot:ToOrientation()
		
		model:PivotTo(CFrame.new(pos) * CFrame.Angles(rX,rY+math.rad(-delta*60),rZ))
	end
	debug.profileend()
	
	debug.profilebegin('EngineShake')
	if deltaCount > 1/20 and ownCart then
		local offset = cartCache[ownFolderName].engineOffset
		if offset then
			local randomX = math.random(-engineShake*100,engineShake*100)/100
			local randomY = math.random(-engineShake*100,engineShake*100)/100
			ownCart.Engine:PivotTo(ownCart.EngineAttachment.WorldCFrame * offset:Inverse() * CFrame.new(randomX,randomY,0))
		end
		deltaCount = 0
	end
	debug.profileend()
end

EDIT: removed the '‘lock to 60fps’ part. all it did was cause more stuttering and uneven memory usage

If the model isn’t fully welded together, you should do that. Pivoting is a lot faster when all the parts are welded, it makes it so it only needs to pivot the root part of the assembly, the other part’s just follow it!

the cart model is fully anchored. would it still help then?

Nope, it should be welded! The weld defines a fixed offset that a part will have relative to another, reducing the pivot calculations.