#gun recoil script using run service to continuously add offsets to player camera

1 messages · Page 1 of 1 (latest)

deep gale
#
local module = {}

local rep = game:GetService("ReplicatedStorage")
local camManager = require(rep.CameraManager).Instance
local camera = game.Workspace.CurrentCamera
local ts = game:GetService("TweenService")
local angle = .6--.6
local upDuration = .05--.05
local downDuration = .08--.08
local rs = game:GetService("RunService")


function module:Recoil()
    local neutral = CFrame.Angles(0,0,0)
    local goal = CFrame.Angles(math.rad(angle),0,0)

    local startTime = tick()
    local conn 
    conn = rs.RenderStepped:Connect(function() 
        local alpha = math.clamp((tick()-startTime)/ upDuration, 0, 1)
        local currentCFrame = neutral:Lerp(goal, alpha)
        camManager:SetOffset("Recoil", currentCFrame)
        if alpha >= 1 then
            conn:Disconnect()
            conn = nil
        end
    end)
    
    repeat task.wait() until not conn

    local startTime = tick()
    conn = rs.RenderStepped:Connect(function()
        local alpha = math.clamp((tick() - startTime) / downDuration, 0, 1)
        local currentCFrame = neutral:Lerp(goal, alpha)
        local x,y,z = currentCFrame:ToEulerAngles()
        currentCFrame = CFrame.Angles(-x,-y,-z)
        camManager:SetOffset("Recoil", currentCFrame)
        if alpha >= 1 then
            camManager:SetOffset("Recoil", nil)
            conn:Disconnect()
            conn = nil
        end
    end)
end

return module

Problem:
The recoil works but the camera doesn't come back to the exact spot that it was previously on. The player always ends up looking slightly higher every time the script runs.
I'd appreciate it if someone could explain why that's happening exactly and if there are some better ways of doing this.

#

the camera manager module adds additional offsets from different camera scripts to the main camera if someones wondering

function CamManager:Enable()
    self.enabled = true    
    rs.RenderStepped:Connect(function()
        local totalOffset = self:GetTotalOffset()
        self.camera.CFrame = self.camera.CFrame * totalOffset    
    end)
end
vague parcel
#

i know you're here Roamer

vague parcel
#

like

#

when u shoot

#

cam gets higher

#

and u gotta take it down by urself

deep gale
#

i mean the script is doing what it's intended to do but it doesn't take it down the same amount that it brought it up for

#

any idea on how to fix that?

vague parcel
#

sorry im too tired to think that much

#

havent slept much

#

good luck tho

deep gale
gusty monolith
#

that's literally the whole point of recoil

#

it isnt supposed to be brought back down

#

on its own

#

the player is supposed to do it

deep gale
deep gale
#

does it even matter?? that wasn't even my question :(