Rookie
Rookie

Reputation: 193

Unity: Raycast Doesn't Hit Child Object's Collider

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.

Upvotes: 0

Views: 2881

Answers (3)

Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10551

Just restrict the raycast for specfic layers

//get the mask to raycast against either the player or enemy layer
 int layer_mask = LayerMask.GetMask("Player", "Enemy");
 //or this would be just player
 //int layer_mask = LayerMask.GetMask("Player");

 //or this would be player, enemy or cows!
 //int layer_mask = LayerMask.GetMask("Player","Enemy","Cows");

 //do the raycast specifying the mask
 if (Physics.Raycast (ray, out hit, distance, layer_mask))
 {

 } 

Upvotes: 0

Just fishing, but isn't it possible that your child collider is hidden inside the parent colider? Raycast then would return only the first hit. You can try RaycastAll as documented here:

https://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html

and loop through all hits in console to know if you are actually getting the collider or not.

Upvotes: 0

pasotee
pasotee

Reputation: 348

I would suggest using using a 3d ray instead of a 2d one. Maybe Camera.screenPointToRay might come in hand. Also, I would suggest you read this first: https://forum.unity3d.com/threads/unity-2d-raycast-from-mouse-to-screen.211708/

Upvotes: 0

Related Questions