Raycast ignore objects ?

Here the raycast went out from camera. What i need is make it ignore hitting any object between camera and player. I got the distance between them but i don’t know how to make it ignore it ?

void FixedUpdate()     {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        // the distance between camera and player
        float cam_player_ignore = Vector3.Distance(gameObject.transform.position, player.transform.position);

        RaycastHit hit;
        if (Physics.Raycast(transform.position, fwd, out hit,100)) {
            print("Ray hit something !");
            // here !!!
        }

        else {
            print (" Nothing ");
        }

Edit>Project Settings>Physics
Have you tried the layer matrix? You can use that to let raycast ignore certain layers.

I’m not looking for layers here.
I need every thing that come up between camera and player will ignored by the raycast.

Can you explain what you are trying to achieve, then we can maybe help. Is it a bullet shooting?

Yes, the raycast went from the main camera and at end there is a crosshair image.
All thing is good until something between the camera and the player blocking the raycast. this thing could be enemy, wall, tree and whatever. To avoid this problem, i calculated the distance that i need the raycast to ignore it.
But i don’t know how to do it.

Sorry, I am not sure if a ray will continue once it hit a collider. That is why I say layers might be your solution.

Did you find any solution? Experiencing same issue

Use a LayerMask to ignore certain layers from your raycast.

If you are not willing to use layers, which is the goto approach for this thing…

You can do a raycast against all objects hit, then filter out the ones you want to ignore. Either by tag name or other means.

You can use link to help you with the filtering also… Something like this:

using linq;
hits = hits.where(x => x.tag != "player").ToArray();
1 Like