I’m making leaning camera system (when you hold down Q/E you lean left or right respecively) using Humanoid CameraOffset, I have had difficulties with the camera clipping through walls, I will provide my attempt at a solution below.
Code
This is the main leaning function.
local function Lean(Direction: string, Toggle: boolean)
print("Leaning ".. Direction)
if Direction == "Left" then
Raycast = workspace:Raycast(Character.Head.Position, LeftCastAttachment.Position, RaycastParam)
elseif Direction == "Right" then
Raycast = workspace:Raycast(Character.Head.Position, RightCastAttachment.Position, RaycastParam)
end
if Raycast and not Raycast.Instance:IsA("BasePart") or Raycast == nil then
if Toggle then
if Direction == "Left" then
LeaningDirection = "Left"
LeanTween = TweenService:Create(Humanoid, CameraTweenInfo, {CameraOffset = Vector3.new(LeanLeftOffset, Humanoid.CameraOffset.Y, Humanoid.CameraOffset.Z)})
LeanTween:Play()
RaycastConnection = RunService.Heartbeat:Connect(UpdateLeanCast)
elseif Direction == "Right" then
LeaningDirection = "Right"
LeanTween = TweenService:Create(Humanoid, CameraTweenInfo, {CameraOffset = Vector3.new(LeanRightOffset, Humanoid.CameraOffset.Y, Humanoid.CameraOffset.Z)})
LeanTween:Play()
end
else
if Direction == "Left" then
LeaningDirection = "None"
LeanTween = TweenService:Create(Humanoid, CameraTweenInfo, {CameraOffset = Vector3.new(0, Humanoid.CameraOffset.Y, Humanoid.CameraOffset.Z)})
LeanTween:Play()
elseif Direction == "Right" then
LeaningDirection = "None"
LeanTween = TweenService:Create(Humanoid, CameraTweenInfo, {CameraOffset = Vector3.new(0, Humanoid.CameraOffset.Y, Humanoid.CameraOffset.Z)})
LeanTween:Play()
end
end
else
warn("LeanBlocked")
end
end
This is the function I made to attempt to prevent clipping if the player moves into a wall
local function UpdateLeanCast()
print(LeaningDirection)
if LeaningDirection == "Left" then
Raycast = workspace:Raycast(Character.Head.Position, Camera.CFrame.LookVector*2, RaycastParam)
elseif LeaningDirection == "Right" then
Raycast = workspace:Raycast(Character.Head.Position, Camera.CFrame.LookVector*2, RaycastParam)
print(Raycast)
elseif LeaningDirection == "None" then
warn("Not Leaning")
RaycastConnection:Disconnect()
end
if Raycast ~= nil then
LeaningDirection = "None"
LeanTween = TweenService:Create(Humanoid, CameraTweenInfo, {CameraOffset = Vector3.new(0, Humanoid.CameraOffset.Y, Humanoid.CameraOffset.Z)})
LeanTween:Play()
RaycastConnection:Disconnect()
end
end
Video of the issue (ignore the music )