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

How to calculate initial angles for center locked camera script?

Asked by 3 years ago

I am working on a camera script (cut down version below).

it is almost there, but there is a problem with the positioning of the camera when switching from the standard mode to the locked version (V on keyboard). This is most noticeable when moving around and rotating the camera before switching.

What I am trying to achieve is for the camera to maintain its current rotation and snap to the offset enabling rotation using the locked mouse.

However what happens is (and the severity depends on the previously set angleX/Y or the initial values of 0) is that the camera snaps to a different position.

Any help would be greatly appreciated!

local userInputService = game:GetService("UserInputService")
local contextActionService = game:GetService("ContextActionService")
local runService = game:GetService("RunService")

local angleX, angleY = 0, 0
local character = script.Parent
local humanoidRoot = character:WaitForChild("HumanoidRootPart")
local camera = game.Workspace.CurrentCamera
local offset = Vector3.new(2, 2, 10)
local min = math.rad(85)
local sensitivity = 1
local locked = false
local stepped = nil

function mouseMove(name, state, inputObject)
    angleX = angleX + (-inputObject.Delta.x*sensitivity/100)
    angleY = angleY + (-inputObject.Delta.y*sensitivity/100)

    angleY = math.clamp(angleY, -min, min)
end

userInputService.InputBegan:Connect(function(input, gameProcessed)
    if input.KeyCode  == Enum.KeyCode.V then
        if not locked then
            enableLockedCamera()            
        else
            enableStandardCamera()
        end
    end
end)

function enableLockedCamera()
    locked = true
    camera.CameraType = "Scriptable"
    userInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
    contextActionService:BindActionToInputTypes("MouseMove", mouseMove, false, Enum.UserInputType.MouseMovement)            

    --I would like to set x/y below so that the camera is positioned relative to it's current rotation (not snap to a different angle). 
    --Currently depending on the characters movement, it snaps to a different angle depending on the values of angleX/Y.
    --angleX = ?
    --angleY = ?

    stepped = runService.RenderStepped:Connect(function()
        camera.CFrame = CFrame.new(humanoidRoot.Position) * CFrame.Angles(0, angleX, 0) * CFrame.Angles(angleY, 0, 0)
        camera.CFrame = camera.CFrame * CFrame.new(offset)
    end)    
end

function enableStandardCamera()
    locked = false
    camera.CameraType = Enum.CameraType.Custom
    contextActionService:UnbindAction("MouseMove")

    if stepped then
        stepped:Disconnect()
    end 
end

Answer this question