Camera not through terrain

hey, how do I stop my camera, which is following a player by a smooth follow script, not go through the terrain?

JAVA please.

You can use a ray cast from the target position towards the camera, if the raycast hits terrain or building then you move the camera forwards to the point of the raycast hit. If you want to ignore certain things like the player you can set them to the ignore raycasts layer or you can use physics raycast all and just loop through all the hits ignoring certain objects (like the player)


var distance : float; // follow distance
var distanceOffset : float; // how much to reduce the follow distance by to avoid objects
var target : Transform; // where the camera is looking at

function Update(){
    var relativePos = transform.position - target.position;
    var hit : RaycastHit;
    if (Physics.Raycast (target.position, relativePos, hit, distance+0.5)) {
        distanceOffset = distance - hit.distance + 0.8; // add near clipping plane distance
        distanceOffset = Mathf.Clamp(distanceOffset,0,distance); // prevent negative distance
        distanceOffset = 0;

This script is part of orbit camera but it can be applied to the follow script by setting the follow distance closer by the distanceOffset variable.


I'm having some troubles getting this script to work with SmoothFollow to stop the camera going through the terrain.

Any chance someone could post the completed Smooth Follow Script with this script merged into it?

I think my issue is here - trying to make use of the distanceOffset variable :

transform.position = target.transform.position;
transform.position -= currentRotation * Vector3.forward * newdistance;

I’ve written a version of a smooth follow camera that is terrain and structure aware. It might be some use…
you can find it here