How to set movement limit to Camera in a top-down 3D game
I have a top-down 3D game where I move an object and the camera follows it. The movement of the player is limited by walls (vertical and horizontal if seen from above) that are on the border of the map. When the player is close to a wall I would want the camera to stop following so it doesn't show the parts that are outisde the walls. If the player is close to a vertical wall (seen from above) the x axis of the camera should be frezzed, if the player is close to a horizontal wall, the z axis of the camera should be frozen and if the player is closed to both horizontal and vertical walls the same but with both axis at the same time. Once the player is far enough from the walls the camera should start moving fluently on the axis that has been frozen. This is a mechanic that all top-down 2D games have.
If the map was a square this would be pretty easy. The problem is that I have a lot of maps with different shapes. For one map, for example, at z=5, the x limit is -10, 10 but at z=50 the x limit is -50,50 and at z=60 the x limit is -30,30 (when I say that at z=5 limits are -10, 10 I mean that at (-10, y,5) and at (10,y,5) there are vertical walls).
I have had some ideas. For example, having a box collider on the camera that only collides with walls (this didn't work at all) or use the code below to detect what GameObjects are around the player at a certain range and if it detects a wall, it freezes the corresponding axis, but this is too computationally expensive and it doesn't work well.
Collider[] colliders = Physics.OverlapSphere(transform.position, playerRadius);
foreach (Collider collider in colliders)
{
if (collider.CompareTag("Wall"))
{
//freeze corresponding axis
}
}
If you have other alternatives I would love to know them. Thanks.