Jittering while trying to make weapon sway

I found a really simple weapon sway code and tried implemeting it on my game, but I constantly got a jittering effect on my weapon, the effect gets easier to notice higher the multiplier is. I managed to recreate the problem in a more simple script, I’m probably making a stupid mistake, I just don’t know where.

-- Place this in starter player scripts
local part = Instance.new("Part", workspace)
part.Size = Vector3.new(1,1,5)
part.Color = Color3.new(1,0,0)
part.Anchored = true
part.CanCollide = false
local camera = workspace.CurrentCamera 



local runService = game:GetService("RunService")
local lastCameraCF = CFrame.new()

function update()
	
	local cframe = CFrame.new()
	cframe = camera.CFrame:ToWorldSpace(CFrame.new(0,-1,0))
	
	local mult = 3
	local swayOffset = CFrame.new()

	local relativeCframe = camera.CFrame.Rotation:ToObjectSpace(lastCameraCF)--get cframe delta.
	local x,y,z = relativeCframe:ToOrientation() --I'm sure there are better ways to get rotation but this will work for now.
	swayOffset = swayOffset:Lerp(CFrame.Angles(math.sin(x)*mult,math.sin(y)*mult,0), 0.1) --calculate the sway using SIN
	lastCameraCF = workspace.CurrentCamera.CFrame.Rotation --update the last cframe
	
	cframe = cframe * swayOffset
	
	part:PivotTo(cframe)
	
end

runService:BindToRenderStep("update", Enum.RenderPriority.Character.Value - 5, update)


Ah, now this brings back painful memories. I remember using the exact same code from the exact post and running into the exact same problem. I can’t remember what I did to fix the problem nor can I find my code anymore, but I don’t recommend this implementation of gun sway as you’re gonna run into some problems in the future when you realise the code is fps dependent.
I’d suggest you use the spring module implementation in the above link, it’s incredibly simple to implement and works even with fps unlockers.

1 Like

Thanks! I’m gonna look into it.

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