Hi. I set off a few days ago to put together a third person script that I could hook into a gun system I’ve been working on. I found numerous resources that worked and got something finally functional. The script here works as it should:
local RS = game:GetService("RunService")
local UIP = game:GetService("UserInputService")
local Plr = game:GetService("Players").LocalPlayer
local UGS = UserSettings():GetService("UserGameSettings")
local Char = Plr.Character or Plr.CharacterAdded:Wait()
local Cam = workspace.CurrentCamera
local xAngle = 0
local yAngle = 0
local Cfg = {
Sens = 0.5,
Goffset = Vector3.new(0, 0, 0),
Loffset = Vector3.new(2, 2, 5)
}
local Ignore = {Char}
UIP.InputChanged:Connect(function(input, isProcessed)
if isProcessed and input.UserInputType ~= Enum.UserInputType.MouseMovement then return end
local delta = input.Delta
xAngle = xAngle - delta.X
yAngle = math.clamp(yAngle - delta.Y * Cfg.Sens, -80, 80)
end)
RS:BindToRenderStep("CameraUpdate", Enum.RenderPriority.Camera.Value, function()
local camSubject = Cam.CameraSubject
if not camSubject then return end
local subject = Char.PrimaryPart
if not subject then return end
local xCFrame = CFrame.Angles(0, math.rad(xAngle), 0)
local anglesCFrame = xCFrame:ToWorldSpace(CFrame.Angles(math.rad(yAngle), 0, 0))
local camPos = subject.Position + Cfg.Goffset
local startCFrame = CFrame.new(camPos):ToWorldSpace(anglesCFrame)
local camCFrame = startCFrame:ToWorldSpace(CFrame.new(Cfg.Loffset))
local camFocus = camCFrame:ToWorldSpace(CFrame.new(0, 0, -Cfg.Loffset.Z))
Cam.Focus = camFocus
Cam.CFrame = camCFrame
UIP.MouseBehavior = Enum.MouseBehavior.LockCenter
UGS.RotationType = Enum.RotationType.CameraRelative
local CameraRay = Ray.new(Char.Head.Position, Cam.CFrame.Position - Char.Head.Position)
local HitPart, HitPosition = game.Workspace:FindPartOnRayWithIgnoreList(CameraRay, Ignore)
Cam.CFrame = (Cam.CFrame - (Cam.CFrame.Position - HitPosition)) + (Char.Head.Position - Cam.CFrame.Position).Unit
end)
The problem I’m facing is with regard to the startCFrame ( I think? ). The function above is togglable, so that the third person lock does not take effect until I equip my gun (tool.Equipped fires and runs the script, tool.Unequipped stops it). However, the script isn’t designed to be togglable, I don’t think, and whenever it is toggled (when I equip my gun), my character snaps towards a specific side of the map, which I think has to do with the camera CFrame being set based on a specific starting CFrame.
I’m not all too familiar with vector math and camera manipulation. What changes can I make so that my character no longer randomly faces one side of the map when the function initializes?