Recoil for viewmodel

Hello, right now I’m creating viewmodel. So I already did shooting with most of animations, but I don’t know how to make camera recoil. I already tried some ways with connections, but they’re really dirty. Can someone explain how to make camera recoil, its should be smooth, and should use Spring modules.

1 Like

Yeah I suggest to use spring modules, that’s what I did when I made a camera recoil, there are a few FPS viewmodel tutorials on the devforums under #resources:community-tutorials, which go over the spring module.

You set the viewmodel CFrame to the camera’s CFrame transformed by some offset every frame to get a “static” viewmodel that’s just fixed relative to the camera. Then you transform that by yet another offset (or lots of offset to compose several effects) that you compute from the recoil. E.g. the recoil could be a single number that goes up when you shoot and gradually goes down with some speed every frame.

Something like

local recoilAmount = 0
local viewmodelOffsets = {
    --BTW order matters here
    base = CFrame.new(1, -2, 3),
    recoil = CFrame.new(),
    headBob = CFrame.new(),
    etcetera = CFrame.new(),
}

function simulateViewmodel(dt)
    recoilAmount = math.max(0, recoilAmount - 1 * dt)
    viewmodelOffsets.recoil = CFrame.Angles(recoilAmount, 0, 0)
end

function getViewmodelCFrame()
    local totalOffset = CFrame.new()
    for _, offset in pairs(viewmodelOffsets) do
        totalOffset *= offset
    end
    return totalOffset
end

function shoot()
    recoilAmount += 1
end

function updateViewmodel(dt)
    simulateViewmodel(dt)
    viewmodel:PivotTo( getViewmodelCFrame() )
end

RunS.RenderStepped:Connect(updateViewmodel)

Solved, succesfully used spring module for that.

By the way, tables that use strings as indexes have no particular order, so you can put keys in any order you want and it will result in the same loop.

If you want a table that goes in a particular order, you have to use numbers for indexes.

1 Like

Actually yeah that’s true, which might be a problem because the order that transforms are applied does matter

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