Prevent camera to go out of terrain


I’m trying to create a map with trees and so on. So I have a Terrain object, some trees and a Camera. Here’s how it looks:

So nothing very complicated. I also did a code to move the main camera when I press arrows of the keyboard. The issue is that I want to prevent the camera to show something else than the map.

For example, you can see on the camera preview that some blue can be seen on the screen. Basically, I guess I should inspect the white line of the camera and see when it touches the edge of the terrain but I really don’t know how to achieve that.

Does someone have some advice?


It is actually not so easy!
Easy way: 1/ constrain you camera position so it can never go too far outside (use clamp function)
2/ plan an external terrain just to avoid seeing void.

Constraining the camera view to the terrain is also doable, but the camera won’t be able to move a lot. For this, you first need to know what your camera sees (that function must be called at each move):

private Vector2[] ComputeWorldCameraBounds()
    Vector2[] cameraBounds = new Vector2[4];

    Ray bottomLeftRay = camera.ViewportPointToRay(new Vector3(0, 0, 0));
    Ray topLeftRay = camera.ViewportPointToRay(new Vector3(0, 1, 0));
    Ray topRightRay = camera.ViewportPointToRay(new Vector3(1, 1, 0));
    Ray bottomRightRay = camera.ViewportPointToRay(new Vector3(1, 0, 0));

    cameraBounds[0] = GetPointAtHeight(bottomLeftRay, 0);
    cameraBounds[1] = GetPointAtHeight(topLeftRay, 0);
    cameraBounds[2] = GetPointAtHeight(topRightRay, 0);
    cameraBounds[3] = GetPointAtHeight(bottomRightRay, 0);

    return cameraBounds;

private Vector2 GetPointAtHeight(Ray ray, float height)
    Vector3 point = ray.origin + (((ray.origin.y - height) / -ray.direction.y) * ray.direction);
    //Debug.Log("GetPointAtHeight :"+ point);
    return new Vector2(point.x, point.z);

Then, you should check whether or not your camera view is inside your terrain coordinates. If not, you can translate back in the right direction.

I know the post is a bit old, but I hope it helps someone someday :slight_smile: