Search Unity

Question Raycast child collider does not hit

Discussion in 'Physics' started by jma00049, Jun 25, 2021.

  1. jma00049

    jma00049

    Joined:
    Feb 21, 2019
    Posts:
    89
    Hello, I have a game where the player moves around a limited zone. The floor is divided into grids (Empty GameObject with box colliders with "is trigger" activated) and I need to throw a ray from my player to the floor so I know the grid where he is but the ray is not hitting any collider.
    These grids are child of an empty GameObject (even no collider) only to move them together but all have the same layer ("Region").
    Here is my code where I throw the ray:
    Code (CSharp):
    1.  
    2. int region = -1;
    3. RaycastHit hit;
    4. LayerMask regionLayer = LayerMask.NameToLayer("Region");
    5. Vector3 raycastOrigin = new Vector3(player.transform.position.x, player.transform.position.y + 2.0f, player.transform.position.z);
    6.  
    7. if (Physics.Raycast(raycastOrigin, -player.transform.up , out hit, Mathf.Infinity, regionLayer))
    8. {
    9.           region = int.Parse(hit.collider.gameObject.name);
    10. }

    Any ideas of what is happening?

    Note 1: My physics configuration allow rays to interact with trigger colliders
    Note 2: I cant use OnTriggerEnter to know where the user is, thats why I use Raycast to the floor.
     
    Last edited: Jun 25, 2021
  2. jma00049

    jma00049

    Joined:
    Feb 21, 2019
    Posts:
    89
    UPDATE:
    If I use:
    Code (CSharp):
    1. RaycastHit[] hits =  Physics.RaycastAll(raycastOrigin, -player.transform.up, Mathf.Infinity);
    with no layermask, it returns the collider, but I need to filter by the layermask and the layer is well asigned.

     
    Last edited: Jun 25, 2021
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    LayerMask.NameToLayer returns the Layer and not the LayerMask. You should use LayerMask.GetMask. I am not saying this is the only problem here but it's certainly one of them.

    Layer 3 is (int)3. The layer-mask of that is (1 << 3) or (binary) 1000 or (int)8.
     
  4. jma00049

    jma00049

    Joined:
    Feb 21, 2019
    Posts:
    89
    That was de solution! Thanks!
     
    MelvMay likes this.