How do i get my camera to go to the end of my ray point?

Hey guys,

i was wondering if someone could help me i have a raycast in the update function and i have created a direction for it. But what i want to do i when i run the game the camera will automatically go to the ray cast end point. Now i have tried this and i can not get it to work can someone please help me thank you :slight_smile:

Here is my script:

 var cameraHolt : Transform;
var Range : float = 50;

   
 var cameraHolt : GameObject;
var Range : float = 50;


function Update () {
    
      if(Input.GetKey(KeyCode.M)){  
      
          var hit : RaycastHit;
    var direction : Vector3  = transform.TransformDirection(Vector3.forward);
      
	Debug.DrawRay(transform.position , direction * Range , Color.blue);
   
   cameraHolt.transform.localPosition = hit.point;
       
      
      }

}

Make sure your ray is indeed hitting something. Try putting a big box with a collider in the direction you are drawing the ray.

Also you use cameraHolt.transform.position at some points and in the Physics.Raycast(…) line you do not. Is this correct?

That’s somewhat confusing: the camera is a child of the script owner object? If so, you can do this:

cameraHolt.transform.localPosition = direction * Range;

This will place the camera exactly at the ray end if the camera is a child of the object to which this script is attached. If it’s an independent object, you can have the same effect with this:

cameraHolt.transform.position = transform.position + direction * Range;

To use hit.point, you should do a Raycast to fill the hit structure with info about the object hit (if any).

For those who are still wondering how to move the camera at the end of a raycast you have to see Ray.GetPoint Unity - Scripting API: Ray.GetPoint.