Raycast - Making ray shoot down vertically -Vector.up

12068-raycast.png

I’m trying to make my raycast shoot downwards from my camera to determine the height from the terrain so I can compensate with an offset. Currently the raycast works however when the camera moves off centre from the terrain the raycast remains pointing at the terrain rather than downward.

Physics.Raycast(transform.position, -Vector3.up, out hit);
offsetDistance = hit.distance;
Debug.DrawLine (transform.position, hit.point, Color.cyan);

I’m guessing that the ray would be infinite if it was to hit “void”.

The issue is that you are not checking to see if the raycast actually hits something. When you move it off of the terrain, the Raycast dies not hit anything and thefore hit is not updated. Try something like:

if (Physics.Raycast(transform.position, -Vector3.up, out hit)) {
   offsetDistance = hit.distance;
   Debug.DrawLine (transform.position, hit.point, Color.cyan);
}