In the gif above, you can see the view model rotating with the direction the mouse is moving. The issue is, I am trying to get the model to rotate about the red highlighted part. I have tried using a combination of CFrame:ToWorldSpace() and CFrame:ToObjectSpace() to apply this rotation each frame, but so far I have been unlucky in my attempts. This is the code I have below:
--calculate gunroot offset
local gunRootOffset = RootPart.CFrame:ToObjectSpace(gunRoot.WorldCFrame)
--swivel towards mouse delta
local delta = UIS:GetMouseDelta()
local deltaOffset = gunRootOffset * CFrame.Angles(math.clamp(-delta.Y*.01, -.05, .05), math.clamp(-delta.X*.01, -.05, .05), 0)
swivelOffset = RootPart.CFrame:ToObjectSpace( RootPart.CFrame
* gunRootOffset:Inverse() *
deltaOffset )
--position set by other scripts, represents base camera position to be modified
local cPos = cameraDataModule.Pos
cPos *= swivelOffset
--position viewmodel
viewModel.PrimaryPart.CFrame = cPos