- Home /
Camera Colliding with Terrain
Hello, I want to make my camera in my racing game collide with the terrain so it cant go through the terrain at all. This is the code I added to my script in order to try and achieve the behaviour I'm looking for:
 using UnityEngine;
 using System.Collections;
 public class SmoothFollow : MonoBehaviour 
 {
     private Ray ray;
     private RaycastHit hit;
     public GameObject player;
     public Transform target;
     void Start()
     {
         ray = new Ray(target.position, target.position - transform.position);
     }
     void Update()
     {
         if (Physics.Raycast(ray, out hit))
         {
              transform.position = ray.GetPoint(hit.distance - 1);
         }
 
         if(cameraNum == -1)
         {
              cameraDistance = Vector3.Distance(target.position, target.position) + 140;
         }
         // Gets the sled position and adds the camera height to it.
         newHeight.y = target.transform.position.y + cameraHeight;
     
         if(Input.GetKeyUp(KeyCode.C) && allowCameraChange)
         {
             ChangeCameraView();        
         } 
     }
 }
Its not giving me any errors its just not doing anything at all besides the normal camera stuff I have going on in the script. Any help or insight would be awesome.
Thanks, Hans
Can I ask maybe a simple question, does your object not move? Your ray is only set once at the start of the level.
A simpler approach I took for terrain camera collision was to do a simple height test at the camera's current x/z position and use that as the camera's y. This is only useful if you only care about terrain collisions.
Answer by testure · Jun 18, 2011 at 06:12 PM
Your ray does not change, so nothing is going to happen. You need to be doing the raycast every frame, or at some regular interval for occlusion/collision testing to work.
Your answer
 
 
             Follow this Question
Related Questions
Terrain collision and specific collision problems . 1 Answer
Making the object collide while moving in the forward dir. (Vector3.forward) 1 Answer
Collision Help 1 Answer
How can I make a sound deploy after colliding with a certain object (or terrain)? 1 Answer
How to let the player collide with animated objects? 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                