Raycasting problems (654451)

I’m trying to make a system in my first-person game so that you can’t interact with an object if it’s behind a wall relative to you, but it isn’t working aand I’m not sure why.

Here’s the code (the object of interaction is in user layer 8):

void FixedUpdate()
    {
        Vector3 fwd = Player.transform.TransformDirection(Vector3.forward);
        
if (Physics.Raycast(Player.transform.position, fwd, range, 1 << 8))
        {
            unObs = true;
        }
        else
        {
            unObs = false;
        }
    }

Is there a collider on the wall to stop the raycast?

Are you possibly starting the raycast “ahead” of the player enough that it starts on the other (far) side of the wall?

Two things come to mind here.

First, you only cast against objects on layer 8, which means if your wall is on another layer it will be ignored by your raycast. Make sure to also include the wall layer into the raycast mask like: 1 << (YOUR_WALL_LAYER_ID) | 1 << 8.

Second, use Debug.DrawRay to check if your ray is starting and heading where you expect it to.

2 Likes

When using a layer mask, rather define a LayerMask variable in your class. In the inspector you can then set the layers nicely without doing bit shifts. Then you can call Physics.Raycast(start, direction, range, myLayerMask)