Ignore Raycast at runtime?

I have a player that when aiming creates a crosshair object at the endpoint of the array. This ray comes from the camera, if the ray detects a hit, it puts the crosshair at the point its hitting, this is fine.

The problem is, if I stand in front of a tall object and aim, the ray hits the object and casts the crosshair on the object behind the player which is obviously not ideal.

I am using hit.distance to determine how close the ray is so is there a way I can say, if the ray distance < amount, ignore all raycasts?


So i actually managed to do it using:

if(hit.distance < 5)
    hit.transform.gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");

But now when my ray looks off into the distance it returns a 0 which in turn gives me an error as there is no object in the way

You might want to try RaycastAll, which returns an array of hits rather than just the first one. You could then discard ones which are too close, and run through the array to find the closest suitable hit.

I found it :slight_smile:

My mistake was I should have been running this code only if a hit was found. Here’s what I’m using:

     //initialize a boolean foundHit and set it to false
     bool foundHit = false;

    //Create a new instance of a raycast hit
    RaycastHit hit = new RaycastHit();

    //fire a ray from the camera forward a distance of 10 units
    foundHit = Physics.Raycast(manager.cam.transform.position, manager.cam.transform.forward, out hit, 20);

    if (foundHit)
        if (hit.distance < 5)
            hit.transform.gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");