Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm studying game development in Unity and I want to create a idle/clicker game like Cow Evolution.

I'm using OnMouseDown, OnMouseDrag and OnMouseUp to move the GameObject around the scene.

Now I want to detect the collision when dropping (OnMouseUp) a GameObject over another GameObject.

Like in this video: https://www.youtube.com/watch?v=3OK77oVV_G0

Assuming there's more than one object below, I must detect which one is with most below the dropped object.

I apologize if it is difficult to understand my English.

Thank you.

share|improve this question

1 Answer 1

For getting all the colliders which are below the touch position , we need to use the RaycastAll function.

This returns an array of hits from which we can determine the GameObject which is at the farthest distance from the camera.

Also take care of the situation where no objects where detected, to avoid the null reference error.

void Update() 
    {
        if (Input.GetMouseButtonUp (0)) 
        {
            RaycastHit[] hits;
            Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            hits = Physics.RaycastAll (camRay);

            Debug.Log("hits "+hits.Length);
            GameObject LastGameObject = null;

            for (int i = 0; i < hits.Length; i++) 
            {
                RaycastHit hit = hits [i];

                if(LastGameObject == null)
                {
                    LastGameObject =  hit.transform.gameObject;

                }
                else 
                {

                    if(Vector3.Distance (LastGameObject.transform.position,Camera.main.transform.position) < Vector3.Distance (hit.collider.transform.position,Camera.main.transform.position))
                    {
                        LastGameObject =  hit.transform.gameObject;
                    }
                }

            }

            if(LastGameObject)
                Debug.Log("last "+LastGameObject.name);
        }


    }
share|improve this answer
    
Hi Hash Buoy, as I learn before, I have to use Physics2D.RaycastAll, but the arguments are different. Can you fix it and show me how to do? –  paulohr Aug 22 at 13:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.