Gun Camera Recoil

Hello, I’m trying to implement weapon recoil, and yes, it’s exactly as I wanted it to be, but I’m facing a problem. I can’t move the camera; it can’t look left or right; it stays in one place. However, when I write camera.CFrame = camera.CFrame * EulerToCFrame(currentRot), the camera becomes overly smooth and doesn’t return to its original position. I demonstrated my issue in the video.

Is currentRot the current orientation? because if so that code is a lil scuffed and Itll be more complicated to help

Either way, what I think you need is to write a function that will rotate the camera up and back down. You could use a loop, but that would be jittery, so Id suggest using render stepped. The code would look something like this:

-- edit these
local RECOIL_ANGLE = 5 -- how much the camera goes up
local RETURN_TIME = 2 -- how long it takes for the camera to go back down

-- takes in a time and returns the position in the return animation from 0 (all the way up) to 1 (fully returned)
function returnFunction(t) -- this you can change however you want to change the way it returns
     return math.clamp(t/RETURN_TIME, 0, 1)
end

function recoil() -- play the recoil animation
     local conn
     local t = 0

     -- shoot up the camera
     camera.CFrame *= CFrame.Angles(math.rad(RECOIL_ANGLE), 0, 0) -- this might need to go into the y axis or z axis instead of the x, idr exactly

     -- play return animation
     conn = RunService.RenderStepped:Connect(function(deltaTime)
          local lastT = t
          t = math.clamp(t + deltaTime, 0, RETURN_TIME)

          -- get the old time and new time to find the change in the return function
          local deltaF = returnFunction(t) - returnFunction(lastT)
          local deltaAngle = -RECOIL_ANGLE * deltaF
          
          -- apply the change in camera angle
          camera.CFrame *= CFrame.Angles(math.rad(deltaAngle), 0, 0)
          
          if t == RETURN_TIME then
               -- has finished return so should stop the animation
               conn:Disconnect()
          end
     end)
end

This code makes the part of the animation where the camera goes up instant, but you can edit it a bit to fix that if you want to.
Something thats very important to keep in mind is that your camera can kind of freak out if the recoil tries to shoot your camera upward beyond facing directly upward, so Id suggest coding a failsafe for this or something along those lines

I am converted this script c# (unity engine) to lua

1 Like