- Home /
How to find all colliders below mouse?
public static bool IsTopmost(GameObject go)
{
RaycastHit[] hits;
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
wp.z = Camera.main.transform.position.z;
hits = Physics.RaycastAll(wp, Vector3.forward, Vector3.Distance(Camera.main.transform.position, go.transform.position) * 2);
if (hits.Length == 0)
{
return false;
}
GameObject topMostSoFar = hits[0].collider.gameObject;
RaycastHit hit;
for (int i = 1; i < hits.Length; i++)
{
hit = hits[i];
if (Compare(topMostSoFar, hit.collider.gameObject) == -1)
{
topMostSoFar = hit.collider.gameObject;
}
}
Debug.Log("finishes method");
return topMostSoFar.name == go.name;
}
My camera position.z = -5, all sprites in the game position.z = 0. This method never finishes, it always enters the first if which says there are no colliders under the mouse position. What do I do wrong here?
EDIT: It turns out my mistake is very stupid, I'm using Physics instead of Physics2D for 2d colliders. How can I check same thing but with 2d raycasting?
And your gameobjects under the mouse all have colliders on them?
Pretty much all of them, yeah. Unless the problem comes from the fact that the colliders are 2d and I'm not using Raycast2d?
Yep, that'll do it. Physics2D and Physics are totally differeny systems - you won't detect a 2D collider with a 3D raycast.
Answer by MapuHoB · Jan 02, 2015 at 09:50 AM
The solution is to use the 2d methods and variable types everywhere and for the direction of the RaycastAll to use Vector2.zero, unless you put Vector2.zero it;s not going to work.
Answer by tanoshimi · Jan 02, 2015 at 09:25 AM
Ummm. Physics2D.RaycastAll?
$$anonymous$$ost likely it is, just it's not clear to me what am I supposed to write for the direction Vec2.zero or?
Your answer

Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
How do I make a Raycast attached to my mouse rotate an object with a script attached on the Y axis? 0 Answers
Raycast - arrow stopped by walls (layer) but not by units (layer) 1 Answer
2 raycasts on the fpwalker/camera 1 Answer