- Home /
2D Raycast over multiple objects not working?
I have a top-down game and I've been trying to find a way to detect mouse clicks on them while there are other objects with colliders on top of it. (In my case the player is clicking and dragging something over top of a tile and then releasing to perform the action.) It seems like most people recommend using RaycastAll to achieve this... however it doesn't seem to detect anything when I use it. I've ensured the object I want to detect has a box collider, so I'm not sure what is happening here. Any advice would be greatly appreciated.
public void Update()
{
RaycastHit[] hits = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition));
foreach (RaycastHit hit in hits)
{
Debug.Log("hit");
}
}
}
hi, how long was your question left awaiting moderation?
Sorry I'm not quite sure what that means.
I mean I'm waiting for my question that needs answering but its waiting for a mod to accept it. How long did you have to wait for yours to be published?
Your code works for me, I've tried in a 3D environment with two cubes placed in a line pointing away from center. Both were raycast-hit-found fine when hovering over just the front one.
Answer by Bunny83 · Feb 16, 2020 at 11:59 AM
My guess is that you just try to mix 2d and 3d physics. Unity has two completely seperate physics engines. Unity uses Box2d for Physics2D and Nvidia's PhysX for (3D) Physics. The two engines do not interact with each other in any way. Both engines do have their own collider type. So you can not use Physics.Raycast against any Collider2D.
2D physics work entirely different from 3D physics. Physics2D.Raycast actually represents a ray in 2d space. If you want to detect if a point overlaps with a 2d collider you want to use Physics2D.OverlapPoint or Physics2D.OverlapPointAll (or even Physics2D.OverlapPointNonAlloc with a pre allocated array if used very frequently).
If you actually use 3d physics and normal 3d Colliders your code should work just fine. If it doesn't for you we're missing some details here. Maybe a screenshot might help.