Search Unity

Can't get Physics2D.Raycast working

Discussion in 'Physics' started by lifetree, Oct 12, 2018.

  1. lifetree

    lifetree

    Joined:
    Mar 28, 2014
    Posts:
    49
    Hi, hope I am not asking something that has already been asked. I looked but was having trouble finding a solution to my issue.

    I am trying to implement a swipe transition into our 2D game. I am trying to use Physics.Raycast, and filter by layermask, since I have multiple colliders overlapping (one of my colliders will be only for the swipe, and it overlaps all other colliders in the scene). It isn't working for me. Here is my code:

    Code (CSharp):
    1.  
    2. RaycastHit hit;
    3. Ray ray = camOrig.ScreenPointToRay(Input.mousePosition);
    4. if (Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.NameToLayer("SwipeCollider")))
    5.  
    I tried my camera with and without the Physics Raycast2D component. It doesn't work with anything I have done. And I know my swipe script works since I tested it using OnMouseOver to test when my mouse was over the collider. The only reason I can't use OnMouseOver for every scene is because I have multiple intersecting 2D colliders.

    Any advice? Is there something that I am missing?

    Thanks in advance for any help!
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,434
    at least If you are using 2D colliders, need to use Physics.Raycast2D
     
  3. lifetree

    lifetree

    Joined:
    Mar 28, 2014
    Posts:
    49
    Thanks for your answer. I tried that as well and that didn't work. The realization that I came to was that I was trying to use ScreenPointToRay, and I learned after asking this here that the aforementioned method only works with 3D vectors. That was my issue, in case it is useful to anyone. For our solution, we actually ended up not using raycasting at all, instead opting for a global scene swipe script using booleans to determine when to swipe on a view by view basis.
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,478
    2D colliders exist on the XY plane so that's where all the queries operate. There is however 2D Physics support for doing "pseudo" 3D raycasts i.e. a ray intersecting the XY plane via the Z axis. Look here.

    Note that doing a raycast like this is extremely wasteful. If you have a screen point then all you need to do is convert it to a world point and use OverlapPoint which is far more efficient than a raycast.