I am aiming my camera and casting a ray from it. Normally, you can get the “end” point by aiming at a target / obstacle like this:
Ray rayCast = new Ray(theCamera.transform.position, theCamera.transform.forward);
float dist = 100f;
RaycastHit hit;
// if this ray hits an obstacle, we can get the "end" point and it's distance
if(Physics.Raycast(rayCast, out hit, dist))
{
// the "end" point or "hit" point can be accessed via hit.point
// we can now illustrate the distance between start and end point
Debug.DrawLine(rayCast.origin, hit.point);
}
But what if there is no obstacle and I wanted to get an “end” point in mid-air (as if there was an imaginary wall right in front of me)? For example, what if the origin point of my ray has a Z (forward axis) of 3, and then I wanted to keep the ray going until it’s Z (forward axis) is at 70? How would I go about coding that?
Ok, like i said above it’s still not clear but i’ll try:
float dist = 100f;
Plane backPlane = new Plane(new Vector3(0,0,-1), new Vector3(0,0,0));
void CastRay()
{
Ray ray = new Ray(theCamera.transform.position, theCamera.transform.forward);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, dist))
{
// we hit an object at "hit.point"
}
else
{
float hitDist;
if (backPlane.Raycast(ray, out hitDist))
{
Vector3 point = ray.GetPoint(hitDist);
// we hit the back plane at "point"
}
}
}
The first argument of the Plane constructor is the plane’s normal in worldspace. Keep in mind you can only hit the plane on the front side. If the plane faces the wrong way you can’t hit it. The second argument is a worldspace position to define the location of the plane. My plane is located at the worlds origin and is facing the -z direction. With a usual setup (camera at 0,1,-10) you should look right at the plane.