# How can i change the hit distance of RaycastHit?

I'm using this script to send a raycast from the center of the camera to objects. It's working fine but only if i'm getting close enough to objects. But for example if it's npc person i want to be able to detect him as "Interactable" from a more distance. How can i change/set the hit distance ?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraRaycast : MonoBehaviour
{
public Camera cam;

void Update()
{
Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
if (hit.transform.tag == "Interactable")
{
print("I'm looking at " + hit.transform.name);
}
else
print("I'm looking at nothing!");
}
}


If you look at the documentation at https://docs.unity3d.com/ScriptReference/Physics.Raycast.html you'll find that the function is overloaded. The very next parameter you can add is distance:

Physics.Raycast(ray, out hit, 100)


Ok, so if you are aware of the Vector3 you are passing as a parameter you are giving to Camera.ViewportToRay(), that is a normalized space (I think that it is a Moebius Space). You are giving to z a 0 parameter, so the ray would reach the start of the viewport, you may play with values between 0.1-1.0 for z, to deal with distance.

Another solution, would be to instance a Ray using the Camera's position as reference, but without using ViewportToRay().

Something like this (you may use transform.forward, instead of TransformDirection):

    public float distance;  /// Distance of your Ray.
public Camera camera;   /// The camera (duh).

void Update()
{
Ray ray = new Ray(camera.transform.position, camera.transform.TransformDirection(0f, 0f, distance));
RaycastHit hit;

if (Physics.Raycast(ray, out hit))
if (hit.transform.tag == "Interactable")
{
print("I'm looking at " + hit.transform.name);
}
else print("I'm looking at nothing!");
}


Thank you! This is what worked for me:

Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);