Prevent custom camera from going through parts

I’m trying to prevent camera from going through parts, however am struggling to find a simple way of accomplishing this

Currently it kinda just stops at the wall, and then goes through. I want it to function similar to the default camera when going towards a wall
ezgif.com-gif-maker (76)

function CameraController:Update()
	local Character = Player.Character
	if not Character then return end
	
	Camera.CameraType = Enum.CameraType.Scriptable
	
	local Positional = CFrame.new(Character.HumanoidRootPart.Position) * self.InitialCameraCFrame
	local CamRotation = Camera.CFrame - Camera.CFrame.Position
	local Rotational = CFrame.Angles(0, math.rad(-self.RotX), 0) * CFrame.Angles(math.rad(-self.RotY), 0, 0)
	
	local Offset = CFrame.new(0, 0.5, self.Zoom)
	
	local NewCameraCFrame = Positional * CamRotation:Lerp(Rotational, 0.75) * Offset
	
	Params.FilterDescendantsInstances = {Character}
	
	local Raycast = workspace:Raycast(
		NewCameraCFrame.Position,
		-NewCameraCFrame.LookVector * 5,
		Params
	)
	
	if Raycast then
		print(Raycast.Instance:GetFullName())
	else
		Camera.CFrame = NewCameraCFrame
	end
end
2 Likes

Use raycasts.
Read more here: Intro to Raycasting

Did you even read my code… :roll_eyes:

Try changing this to this

local Raycast = workspace:Raycast(
		NewCameraCFrame.Position + Vector3.new(5, 0, 0),
		-NewCameraCFrame.LookVector * 5,
		Params
	)

I think whats happening is when the camera gets behind the wall it wont detect any result because its behind it. If you add an offset to that starting position that might work

Managed to figure it out, works perfectly

local Raycast = workspace:Raycast(
	Character:GetPivot().Position,
	-NewCameraCFrame.LookVector * self.Zoom,
	Params
)

if Raycast then
	local Distance = (Character.HumanoidRootPart.Position - Raycast.Position).Magnitude
	Offset = CFrame.new(0, 0.5, math.floor(Distance))
	NewCameraCFrame = Positional * CamRotation:Lerp(Rotational, 0.75) * Offset
end
1 Like