Creating Weapon Sway With Math

Im trying to get the weapon sway to look something like this:
Example.wmv (1.2 MB)
without using animations, how could i do this?

-This is the closest ive gotten in my script

	local SetViewPosition = RunService.RenderStepped:Connect(function (dt)

		local CurrentCFrame = V_Viewmodel:GetPivot()

		if HumRoot.AssemblyLinearVelocity.Magnitude < 1 then

			local DefaultGunShake = math.sin(tick() * 2) * 0.05
			local TargetCFrame = Camera.CFrame * CFrame.new(0 + DefaultGunShake,-4.5 + DefaultGunShake, 0.55)

			V_Viewmodel:PivotTo(TargetCFrame)
			t = 0

		else
			t += dt
			local GunShake = math.sin(t * 5) * 0.1
			V_Viewmodel:PivotTo(Camera.CFrame * CFrame.new(0 + GunShake,-4.5 + GunShake, 0.55))

		end

	end)

The only problem with this is that it kinda snaps when switching standing to walking.
–edit i meant this video
SwayExample.wmv (1.3 MB)

1 Like

Instead of having two states, mix those two sources of shake using a lerp. Use the players velocity as the ‘alpha’, and add some smoothing to it by averaging over the last couple velocities. E.g:

wiggleFactor = (previousVelocity + Velocity.Magnitude) / 2.0
previousVelocity = Velocity.Magnitude
1 Like

This sounds like it’ll work great, I’ll try it out soon here and let you know how it worked when i get back!

sorry about this but could you show me how i should implement this into my script?

Nevermind! I got something working, fixed up a lerped CFrame, heres the code, ill probably adjust it later.

	local SetViewPosition = RunService.RenderStepped:Connect(function (dt)

		local CurrentCFrame = V_Viewmodel:GetPivot()

		if HumRoot.AssemblyLinearVelocity.Magnitude < 1 then

			local DefaultGunShake = math.sin(tick() * 2) * 0.05
			local TargetCFrame = Camera.CFrame * CFrame.new(0 + DefaultGunShake,-4.5 + DefaultGunShake, 0.55)
			local CurrentCFrame = V_Viewmodel:GetPivot():Lerp(TargetCFrame, 0.9)

			V_Viewmodel:PivotTo(CurrentCFrame)
			t = 0

		else
			t += dt
			local GunShake = math.sin(t * 5) * 0.1
			V_Viewmodel:PivotTo(Camera.CFrame * CFrame.new(0 + GunShake,-4.5 + GunShake, 0.55))

		end

	end)

This is a interesting way of doing it. Let me know if theres anything else.

1 Like

Is there a better way i couldve done this? what would you suggest?

Im just not the biggest fan of lerping cause it doesnt look great when you turn your camera fast

Sorry I should have clarified, I meant for you to lerp the magnitude (the 0.05 or 0.1 after your sins) not the CFrames, which would indeed have that problem.

1 Like

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