3rd person mouse locked camera stop at walls

Hello,

I am using this script to achieve a 3rd person camera that follows the mouse.

The problem with that script is that the camera will pass through walls as you can see here:

Gif with problem

https://gyazo.com/f166d80fa1d1991944fdfb455a40e976

I am not sure how to make it stop at walls like in most games. I thought of using raycasting from the player to the camera. Unfortunately that seems to not work reliably.

function checkCameraLos(rootPart, cameraCFrame)
	local ray = Ray.new(rootPart.Position, cameraCFrame.p)
	local hit, pos, norm, mat = game.Workspace:FindPartOnRayWithIgnoreList(ray, {rootPart.Parent})
	if hit then
		print(hit, pos, cameraCFrame)
	end
end

I expect this print to only happen when the camera is obstructed. But it does not work in all cases and sometimes it prints even when not obstructed.

Any ideas or suggestions on how to implement the camera stop on walls?

Thanks.

the second parameter of a raycast is a direction. not a second position. to calculate the direction you subtract the camera position from the origin and multiply the unit of that by the distance between the camera and the player.

function checkCameraLos(rootPart, cameraCFrame)
        local distance = (cameraCFrame.p-rootPart.Position).magnitude + 5 -- +5 to make sure it hits a    wall if the camera is in it
	local ray = Ray.new(rootPart.Position, (cameraCFrame.p-rootpart.Position).unit*distance)
	local hit, pos, norm, mat = game.Workspace:FindPartOnRayWithIgnoreList(ray, {rootPart.Parent})
	if hit then
		print(hit, pos, cameraCFrame)
	end
end

this should eventually work better than the way you had it :slight_smile:

2 Likes

Oh silly me, thank you for pointing that out. Indeed it solves the problem. Now I need to implement the actual camera stopping. Thank you.