- Home /
How can I do a 2D raycast against one specific collider?
For 3D colliders ( Collider
), I can do:
collider.Raycast(ray, out hit, rayLength)
But for 2D colliders ( Collider2D
), there is no Raycast
method.
There's this angry feature request from more than a year ago, but no response.
I cannot use layer masks, because I cannot predict on which layer my collider will be.
(How) can I do it?
$$anonymous$$aybe with Collider2D.OverlapPoint, if frontal
Can't You just treat it as normal collider? Collider2D col; col.collider.Raycast(...);
actually i am going to use $$anonymous$$Depth and maxDepth but it's ridiculous they haven't fixed it yet
Answer by Glurth · Mar 07, 2015 at 02:35 PM
Not sure if you want your rays to be exclusively on a 2D surface, If so, perhaps using the Physics2D raycast functions will work for your situation?
http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
If you want to detect an intersection with a FACE, rather than a EDGE, then the Physics (3D) raycast, should work.
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Not sure if you bothered to read it. He needs 2D raycast from point A to point B and get if one particular Collider2D was hit and it's not possible right now with Physics2D or Collider2D.
Don't know if he can but i definitely can't switch to 3D physics.
Answer by TheAnosmic · Nov 25, 2019 at 10:58 PM
Hope it will help others, I needed to check for intersection in the same scenario, I used this:
collider.bounds.IntersectRay()
Answer by indolence · Mar 04, 2021 at 01:00 PM
I was trying to solve a similar problem on my project and ended up with this workaround solution. I'm not sure if it's the best, but it seems to get the job done.
The key here is that one of the overload methods for Physics2D.Raycast lets you output an array or list of results instead of just getting the first hit. Then you can check through your results list and find the one that matches the game object you're checking against.
List<RaycastHit2D> resultsList = new List<RaycastHit2D>();
Physics2D.Raycast(raycastStart, raycastDirection, contactFilter, resultsList, rayCheckDist);
foreach (RaycastHit2D result in resultsList)
{
Debug.Log(result.collider.gameObject);
if (result.collider.gameObject == gameObjectToCheckFor)
{whatever you want to happen here}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613185156im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
why Raycast2D doesn't work properly? 0 Answers
Physics 2d raycaster from EventSystems for overlapped colliders 0 Answers
RaycastHit2D problem with PolygonCollider2D 2 Answers
OnCollisionEnter fires, but OnCollisionExit does not 1 Answer
Is this a correct way to have multiple different compound colliders in one gameobject? 1 Answer