How can I smoothly move the camera up?

Hi, I’m currently making a gun system and I would like to add recoil to the gun for obvious reasons. I’ve put together a really small chunk of code to move the camera small bit upward whenever the player shoots. The problem is is that it’s very skippy, here’s a video of the gun:


As you can see it looks very weird, so to counter this I want to smoothly move the camera upwards instead of jolting it upwards. Note that I do not want it in scriptable mode as this would break the gun and the mouse could move around the screen freely. Here’s the code:

mouse.Button1Down:Connect(function()
	
	cam = game.Workspace.CurrentCamera
	targetCFrame = cam.CoordinateFrame * CFrame.Angles( math.rad(1), math.rad(0), math.rad(0)) * CFrame.new(0,0,0)

	Recoil = game:GetService("RunService").RenderStepped:Connect(function(dt)
		cam.CoordinateFrame = cam.CoordinateFrame:Lerp(targetCFrame, 0.7)
		Recoil:Disconnect()
	end)
end)
1 Like

The problem is, that since you are instantly :Disconnect()ing the .RenderStepped, you only provide the recoil one frame to move.

To use :Lerp for a Tween-like effect, you need to use a loop(preferably a for loop), to gradually shift the midpoint over time.

Example:


for i = 0, 1, .01 do
    cam.CoordinateFrame = cam.CoordinateFrame:Lerp(TargetCFrame,i) --use Lerp to find the midpoint between start and end point
    Run.RenderStepped:Wait()
end

I would look into this post, as it has a very good example.

1 Like

Yeah but if I do this with an automatic weapon there would be multiple .RenderStepped functions being ran at the same time which will obviously cause issues.

That’s why I recommend running a for loop with a fast incline so it can finish before the next one starts. Unfortunately if you want it to be smooth, you are going to need to use more than one frame, or there is no way to portray the tween effect.

1 Like

This causes more issues like you not being able to turn while shooting due to it lerping to a certain position.

Look at the example in the link I posted above. It adds on to the current camera CFrame every frame refresh, so that you don’t get this problem. This it accounts for the Delta plus the recoil.