I have a tile based game. I place towers as child objects of tiles. I want to be able to detect mouse clicks on towers but not tiles, with raycasting. Both tiles and the towers have 2d box colliders. I can detect clicks on tiles but raycast won't detect the ones on the towers. How can I solve this problem. Thanks.
Here is my code for raycasting:
if (Input.GetMouseButtonDown(0))
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
ray.origin = camera.transform.position;
RaycastHit2D hit = Physics2D.Raycast(camera.transform.position, -Vector2.up, 50, 8);
if (hit.collider != null && !EventSystem.current.IsPointerOverGameObject())
{
Debug.Log(hit.collider.transform.tag);
//Transform objectHit = hit.transform;
}
}
}
When I mask the tiles (here layer 8) I get nothing. It seems rays never hit the towers although towers (like tiles) also have a 2d box collider.