How to optimize my acid trail script

I wrote an “Acid path” script were whenever you walk an acid part gets cloned on the characters feet.

My problem now is that the script works fine but when i try it in-game it causes alot of lag for me and my friend. I changed the script so that the visuals are client-sided but it still lags.

Script ```lua
function Chemicals.CreateAcid(player, Handle)
local char = player.Character

if listener then 
	listener:Disconnect()	 
end

listener = char.Humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(function()
	if db then
		db = false
		local Acid = game.ReplicatedStorage.Acid:Clone()		
		if char.Humanoid.FloorMaterial ~= Enum.Material.Air and char.Humanoid.MoveDirection ~= Vector3.new(0,0,0) then
			Acid.Position = char.HumanoidRootPart.Position - Vector3.new(0, (char.Humanoid.HipHeight + 1), 0)
			Acid.BrickColor = Handle.Fluid.BrickColor	
			Acid.Bubbles.Enabled = true			
			Acid.Parent = workspace
		end			
		
		wait(.3)
		Debris:AddItem(Acid, 3)
		db = true
	end
end)	

end

The thing is with MoveDirection, it doesn’t update if the player keeps going in the same direction. Sure, there may be small deviations, but if they just start out and don’t turn their camera, they can just walk perfectly straight. This will make the function run only initially when they begin to walk, not all the way. You should probably use RunService.RenderStepped for character scripts like this. Inside that, you can check if the player is moving or not:

RunService.RenderStepped:Connect(function(deltaTime) --time between last frame

    if hum.MoveDirection:Dot(hum.MoveDirection) > 0.1 then

        --code--

    end

end)

RenderStepped is more reliable and less laggy in these cases.

Why use the dot product? Well, magnitude is quite expensive due to square roots, so you should try to avoid it as much as possible. The dot product of a vector with itself is always the magnitude squared. So, if the magnitude is 0, so is the dot product. I put the threshold at 0.1 because we don’t want to create too many acid parts if they move ever so slightly (on mobile, they can control their speed easily via the thumbstick). You may increase that amount if needed.

Also, just make sure you’re deleting these parts afterward. Making them permanent will cause lag eventually.

1 Like

Thanks i really appriciate it and will try your tips.

1 Like

So I configured the script so that it used “RenderStepped” instead but it still seems to lag alot? It seems like everytime i clone in the “part” the fps drops.