- Home /
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.
Answer by spinaljack · Sep 23, 2010 at 02:45 PM
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)
e.g.
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)) { Debug.DrawLine(target.position+Vector3.up,hit.point); distanceOffset = distance - hit.distance + 0.8; // add near clipping plane distance distanceOffset = Mathf.Clamp(distanceOffset,0,distance); // prevent negative distance }else{ 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.
Answer by JeffAU · Mar 16, 2011 at 10:46 PM
Heya,
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 :
newdistance=distance-distanceOffset;
transform.position = target.transform.position;
transform.position -= currentRotation * Vector3.forward * newdistance;
Answer by whydoidoit · Mar 22, 2012 at 10:03 PM
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
Your answer
![](https://koobas.hobune.stream/wayback/20220613073723im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
OnMouseDown on what? Camera Movement Help. 1 Answer
Camera to follow the mouse to move to create the point 0 Answers