Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Raycasting problems

Discussion in 'Scripting' started by Balistic_penguin, Feb 6, 2017.

  1. Balistic_penguin

    Balistic_penguin

    Joined:
    Jan 18, 2017
    Posts:
    107
    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):
    Code (csharp):
    1. void FixedUpdate()
    2.     {
    3.         Vector3 fwd = Player.transform.TransformDirection(Vector3.forward);
    4.        
    5. if (Physics.Raycast(Player.transform.position, fwd, range, 1 << 8))
    6.         {
    7.             unObs = true;
    8.         }
    9.         else
    10.         {
    11.             unObs = false;
    12.         }
    13.     }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,814
    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?
     
  3. ardo314

    ardo314

    Joined:
    Jul 7, 2012
    Posts:
    345
    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.
     
    Kurt-Dekker and omegabytestudio like this.
  4. VengeanceDesign

    VengeanceDesign

    Joined:
    Sep 7, 2014
    Posts:
    84
    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)