Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How Do I Change The Shoulder Camera Script In The "Auto Rifle" Model By Roblox To Change Plr Camera?

Asked by 3 years ago

I want to be able to manipulate the player's camera to a certain spot but I can't do it because the shoulder camera script in the "Auto Rifle" model by Roblox is not allowing for the camera CFrame to be changed. Please help thank you!

(Shoulder Camera Script in the "Auto Rifle" model by Roblox > AR > WeaponsSystem > Libraries > ShoulderCamera)

local ContextActionService = game:GetService("ContextActionService")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
local GuiService = game:GetService("GuiService")
local Players = game:GetService("Players")

local UserGameSettings = UserSettings():GetService("UserGameSettings")

local LocalPlayer = Players.LocalPlayer
if RunService:IsClient() then
    while not LocalPlayer do
        Players.PlayerAdded:Wait()
        LocalPlayer = Players.LocalPlayer
    end
end
local Settings = UserSettings()
local GameSettings = Settings.GameSettings

local CAMERA_RENDERSTEP_NAME = "ShoulderCameraUpdate"
local ZOOM_ACTION_NAME = "ShoulderCameraZoom"
local SPRINT_ACTION_NAME = "ShoulderCameraSprint"
local CONTROLLABLE_HUMANOID_STATES = {
    [Enum.HumanoidStateType.Running] = true,
    [Enum.HumanoidStateType.RunningNoPhysics] = true,
    [Enum.HumanoidStateType.Freefall] = true,
    [Enum.HumanoidStateType.Jumping] = true,
    [Enum.HumanoidStateType.Swimming] = false,
    [Enum.HumanoidStateType.Landed] = true
}

-- Gamepad thumbstick utilities
local k = 0.5
local lowerK = 0.9
local function SCurveTransform(t)
    t = math.clamp(t, -1,1)
    if t >= 0 then
        return (k*t) / (k - t + 1)
    end
    return -((lowerK*-t) / (lowerK + t + 1))
end

local DEADZONE = 0.25
local function toSCurveSpace(t)
    return (1 + DEADZONE) * (2*math.abs(t) - 1) - DEADZONE
end

local function fromSCurveSpace(t)
    return t/2 + 0.5
end

-- Applies a nonlinear transform to the thumbstick position to serve as the acceleration for camera rotation.
-- See https://www.desmos.com/calculator/xw2ytjpzco for a visual reference.
local function gamepadLinearToCurve(thumbstickPosition)
    return Vector2.new(
        math.clamp(math.sign(thumbstickPosition.X) * fromSCurveSpace(SCurveTransform(toSCurveSpace(math.abs(thumbstickPosition.X)))), -1, 1),
        math.clamp(math.sign(thumbstickPosition.Y) * fromSCurveSpace(SCurveTransform(toSCurveSpace(math.abs(thumbstickPosition.Y)))), -1, 1))
end


-- Remove back accessories since they frequently block the camera
local function isBackAccessory(instance)
    if instance and instance:IsA("Accessory") then
        local handle = instance:WaitForChild("Handle", 5)
        if handle and handle:IsA("Part") then
            local bodyBackAttachment = handle:WaitForChild("BodyBackAttachment", 5)
            if bodyBackAttachment and bodyBackAttachment:IsA("Attachment") then
                return true
            end

            local waistBackAttachment = handle:WaitForChild("WaistBackAttachment", 5)
            if waistBackAttachment and waistBackAttachment:IsA("Attachment") then
                return true
            end
        end
    end

    return false
end

local function removeBackAccessoriesFromCharacter(character)
    for _, child in ipairs(character:GetChildren()) do
        coroutine.wrap(function()
            if isBackAccessory(child) then
                child:Destroy()
            end
        end)()
    end
end

local descendantAddedConnection = nil
local function onCharacterAdded(character)
    removeBackAccessoriesFromCharacter(character)
    descendantAddedConnection = character.DescendantAdded:Connect(function(descendant)
        coroutine.wrap(function()
            if isBackAccessory(descendant) then
                descendant:Destroy()
            end
        end)()
    end)
end

local function onCharacterRemoving(character)
    if descendantAddedConnection then
        descendantAddedConnection:Disconnect()
        descendantAddedConnection = nil
    end
end

-- Set up the Local Player
if RunService:IsClient() then
    if LocalPlayer.Character then
        onCharacterAdded(LocalPlayer.Character)
    end
    LocalPlayer.CharacterAdded:Connect(onCharacterAdded)
    LocalPlayer.CharacterRemoving:Connect(onCharacterRemoving)
end


local ShoulderCamera = {}
ShoulderCamera.__index = ShoulderCamera
ShoulderCamera.SpringService = nil

function ShoulderCamera.new(weaponsSystem)
    local self = setmetatable({}, ShoulderCamera)
    self.weaponsSystem = weaponsSystem

    -- Configuration parameters (constants)
    self.fieldOfView = 70
    self.minPitch = math.rad(-75) -- min degrees camera can angle down
    self.maxPitch = math.rad(75) -- max degrees camera can cangle up
    self.normalOffset = Vector3.new(2.25, 2.25, 10.5) -- this is the camera's offset from the player
    self.zoomedOffsetDistance = 8 -- number of studs to zoom in from default offset when zooming
    self.normalCrosshairScale = 1
    self.zoomedCrosshairScale = 0.75
    self.defaultZoomFactor = 1
    self.canZoom = true
    self.zoomInputs = { Enum.UserInputType.MouseButton2, Enum.KeyCode.ButtonL2 }
    self.sprintInputs = { Enum.KeyCode.LeftShift }
    self.mouseRadsPerPixel = Vector2.new(1 / 480, 1 / 480)
    self.zoomedMouseRadsPerPixel = Vector2.new(1 / 1200, 1 / 1200)
    self.touchSensitivity = Vector2.new(1 / 100, 1 / 100)
    self.zoomedTouchSensitivity = Vector2.new(1 / 200, 1 / 200)
    self.touchDelayTime = 0.25 -- max time for a touch to count as a tap (to shoot the weapon instead of control camera),
                               -- also the amount of time players have to start a second touch after releasing the first time to trigger automatic fire
    self.recoilDecay = 2 -- higher number means faster recoil decay rate
    self.rotateCharacterWithCamera = true
    self.gamepadSensitivityModifier = Vector2.new(0.85, 0.65)
    -- Walk speeds
    self.zoomWalkSpeed = 6
    self.normalWalkSpeed = 12
    self.sprintingWalkSpeed = 20

--Continued

1 answer

Log in to vote
0
Answered by 3 years ago
--Continuation
    -- Current state
    self.enabled = false
    self.yaw = 0
    self.pitch = 0
    self.currentCFrame = CFrame.new()
    self.currentOffset = self.normalOffset
    self.currentRecoil = Vector2.new(0, 0)
    self.currentMouseRadsPerPixel = self.mouseRadsPerPixel
    self.currentTouchSensitivity = self.touchSensitivity
    self.mouseLocked = true
    self.touchPanAccumulator = Vector2.new(0, 0) -- used for touch devices, represents amount the player has dragged their finger since starting a touch
    self.currentTool = nil
    self.sprintingInputActivated = false
    self.desiredWalkSpeed = self.normalWalkSpeed
    self.sprintEnabled = false -- true means player will move faster while doing sprint inputs
    self.slowZoomWalkEnabled = false -- true means player will move slower while doing zoom inputs
    self.desiredFieldOfView = self.fieldOfView
    -- Zoom variables
    self.zoomedFromInput = false -- true if player has performed input to zoom
    self.forcedZoomed = false -- ignores zoomedFromInput and canZoom
    self.zoomState = false -- true if player is currently zoomed in
    self.zoomAlpha = 0
    self.hasScope = false
    self.hideToolWhileZoomed = false
    self.currentZoomFactor = self.defaultZoomFactor
    self.zoomedFOV = self.fieldOfView
    -- Gamepad variables
    self.gamepadPan = Vector2.new(0, 0) -- essentially the amount the gamepad has moved from resting position
    self.movementPan = Vector2.new(0, 0) -- this is for movement (gamepadPan is for camera)
    self.lastThumbstickPos = Vector2.new(0, 0)
    self.lastThumbstickTime = nil
    self.currentGamepadSpeed = 0
    self.lastGamepadVelocity = Vector2.new(0, 0)

    -- Occlusion
    self.lastOcclusionDistance = 0
    self.lastOcclusionReachedTime = 0 -- marks the last time camera was at the true occlusion distance
    self.defaultTimeUntilZoomOut = 0
    self.timeUntilZoomOut = self.defaultTimeUntilZoomOut -- time after lastOcclusionReachedTime that camera will zoom out
    self.timeLastPoppedWayIn = 0 -- this holds the last time camera popped nearly into first person
    self.isZoomingOut = false
    self.tweenOutTime = 0.2
    self.curOcclusionTween = nil
    self.occlusionTweenObject = nil

    -- Side correction (when player is against a wall)
    self.sideCorrectionGoalVector = nil
    self.lastSideCorrectionMagnitude = 0
    self.lastSideCorrectionReachedTime = 0 -- marks the last time the camera was at the true correction distance
    self.revertSideCorrectionSpeedMultiplier = 2 -- speed at which camera reverts the side correction (towards 0 correction)
    self.defaultTimeUntilRevertSideCorrection = 0.75
    self.timeUntilRevertSideCorrection = self.defaultTimeUntilRevertSideCorrection -- time after lastSideCorrectionReachedTime that camera will revert the correction
    self.isRevertingSideCorrection = false

    -- Datamodel references
    self.eventConnections = {}
    self.raycastIgnoreList = {}
    self.currentCamera = nil
    self.currentCharacter = nil
    self.currentHumanoid = nil
    self.currentRootPart = nil
    self.controlModule = nil -- used to get player's touch input for moving character
    self.random = Random.new()

    return self
end

function ShoulderCamera:setEnabled(enabled)
    if self.enabled == enabled then
        return
    end
    self.enabled = enabled

    if self.enabled then
        RunService:BindToRenderStep(CAMERA_RENDERSTEP_NAME, Enum.RenderPriority.Camera.Value - 1, function(dt) self:onRenderStep(dt) end)
        ContextActionService:BindAction(ZOOM_ACTION_NAME, function(...) self:onZoomAction(...) end, false, unpack(self.zoomInputs))
        ContextActionService:BindAction(SPRINT_ACTION_NAME, function(...) self:onSprintAction(...) end, false, unpack(self.sprintInputs))

        table.insert(self.eventConnections, LocalPlayer.CharacterAdded:Connect(function(character) self:onCurrentCharacterChanged(character) end))
        table.insert(self.eventConnections, LocalPlayer.CharacterRemoving:Connect(function() self:onCurrentCharacterChanged(nil) end))
        table.insert(self.eventConnections, workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(function() self:onCurrentCameraChanged(workspace.CurrentCamera) end))
        table.insert(self.eventConnections, UserInputService.InputBegan:Connect(function(inputObj, wasProcessed) self:onInputBegan(inputObj, wasProcessed) end))
        table.insert(self.eventConnections, UserInputService.InputChanged:Connect(function(inputObj, wasProcessed) self:onInputChanged(inputObj, wasProcessed) end))
        table.insert(self.eventConnections, UserInputService.InputEnded:Connect(function(inputObj, wasProcessed) self:onInputEnded(inputObj, wasProcessed) end))

        self:onCurrentCharacterChanged(LocalPlayer.Character)
        self:onCurrentCameraChanged(workspace.CurrentCamera)

        -- Make transition to shouldercamera smooth by facing in same direction as previous camera
        local cameraLook = self.currentCamera.CFrame.lookVector
        self.yaw = math.atan2(-cameraLook.X, -cameraLook.Z)
        self.pitch = math.asin(cameraLook.Y)

        self.currentCamera.CameraType = Enum.CameraType.Scriptable

        self:setZoomFactor(self.currentZoomFactor) -- this ensures that zoomedFOV reflecs currentZoomFactor

        workspace.CurrentCamera.CameraSubject = self.currentRootPart

        self.occlusionTweenObject = Instance.new("NumberValue")
        self.occlusionTweenObject.Name = "OcclusionTweenObject"
        self.occlusionTweenObject.Parent = script
        self.occlusionTweenObject.Changed:Connect(function(value)
            self.lastOcclusionDistance = value
        end)

        -- Sets up weapon system to use camera for raycast direction instead of gun look vector
        self.weaponsSystem.aimRayCallback = function()
            local cameraCFrame = self.currentCFrame
            return Ray.new(cameraCFrame.p, cameraCFrame.LookVector * 500)
        end
    else
        RunService:UnbindFromRenderStep(CAMERA_RENDERSTEP_NAME)
        ContextActionService:UnbindAction(ZOOM_ACTION_NAME)
        ContextActionService:UnbindAction(SPRINT_ACTION_NAME)

        if self.currentHumanoid then
            self.currentHumanoid.AutoRotate = true
        end

        if self.currentCamera then
            self.currentCamera.CameraType = Enum.CameraType.Custom
        end

        self:updateZoomState()

        self.yaw = 0
        self.pitch = 0

        for _, conn in pairs(self.eventConnections) do
            conn:Disconnect()
        end
        self.eventConnections = {}

        UserInputService.MouseBehavior = Enum.MouseBehavior.Default
        UserInputService.MouseIconEnabled = true
    end
end
0
check out my other post "How Do I Change The Shoulder Camera Script In The "Auto Rifle" Model By Roblox Continuation?" for the rest of the code. MrSarp_shoot 37 — 3y
Ad

Answer this question