Search Unity

Camera and Terrain

Discussion in 'Scripting' started by Tom163, Nov 30, 2007.

  1. Tom163

    Tom163

    Joined:
    Nov 30, 2007
    Posts:
    1,290
    I've just started with Unity, but I've already hit a first problem the wiki and a forum search revealed nothing about:

    I have a player object that I follow in 3rd person (Mouse Orbit script).

    How can I prevent the camera from going below the terrain? If I put a collider on the camera, it bounces my player object up into the sky every time the camera hits the terrain. :-(
     
  2. bigkahuna

    bigkahuna

    Joined:
    Apr 30, 2006
    Posts:
    5,434
    Good question. I also did a search for this a while back and the best solution seemed to involve using ray casting in all directions to check distances to colliders. I never found a good script or solution for this though, if anyone has such a thing it would make a great addition to the wiki!
     
  3. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    Make sure you have a mesh collider on the ground object and then cast a ray downwards from the camera to measure its distance to the ground (using RaycastHit.distance). Basically, you subtract the measured distance from the desired floating height - the difference will be negative if the camera is too high, positive if it is too low and zero if it is just right. Add this difference to the y-coordinate of the camera to give the correct height. If you do this every frame, you should find the camera tracks the surface it is standing on.

    A word of caution, though - this type of camera is very unforgiving if the ground surface is rough (you get a very bumpy picture). You can handle this with a little bit of physics, but it's slightly more complicated than this simple method.