Search Unity

Physics2D.Raycast ignores the front object and picks behind it randomly

Discussion in 'Physics' started by jGate99, May 29, 2019.

  1. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,945
    Hi there,

    I have a 2D game with sprites and orthographic camera.

    When i use following code, then in most cases object behind other objects gets picked. I say mostly because sometime it picks the front object too.

    As im not really good with raycasting so hoping someone can assist me.

    Thanks
    Code (CSharp):
    1.  
    2. Vector3 worldPoint = CameraMain.ScreenToWorldPoint(ScreenPosition);
    3. Collider2D collider2D =  Physics2D.Raycast(worldPoint, Vector2.zero, 0  ).collider;
    4. //mostly collider2D is behind another object
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    Obviously 2D physics is 2D so the Z order or rendering order has nothing to do with it. Also, if you want to check colliders overlapping a point, don't use a degenerate ray (zero direction and zero length), use Physics2D.OverlapPoint.

    That said, there is the much slower pseudo-3D raycast for true 3D rays which after finding the 2D results, sorts the results based upon the Z order and the direction of the ray here. Note though that this knows nothing about sorting-groups etc and that 2D physics only knows about the XY plane.
     
    jGate99 likes this.
  3. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,945
    Thanks for your reply, ill try the Z order based and hopefully it works as expected.
     
  4. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,945

    Is there a Physics2D raycast option that returns the sprite based on higher sort order value?
     
  5. unitj75

    unitj75

    Joined:
    May 30, 2022
    Posts:
    26
    I'm running into a similar issue. I was using Z values closer to the camera which appeared to work, but it may have been a fluke. If I have multiple objects that can overlap (on the different layers and different order), how can I use OnPointerClick to always pick the front object?