Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raycasting to find mouseclick on Object in unity 2d games

I am trying to delete the object on which the mouse is clicked. I am making a 2D game using the new Unity3D 4.3. Here is the code I'm using

void Update () {

    if (Input.GetMouseButtonDown(0)) 
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if(Physics.Raycast(ray,out hit))
        {
            isHit = false;
            Destroy(GameObject.Find(hit.collider.gameObject.name));

        }
    }

}

The control is not entering the inner if loop. (isHit is not being set as false).

like image 259
Bimal Bose B S Avatar asked Dec 14 '13 13:12

Bimal Bose B S


1 Answers

First attach any type of 2D collider to your GameObject, then pick one of those solutions;

1st Case - If there are more than 1 GameObject on top of each other, and you try to understand specific GameObject is clicked:

void Update ()
{
    if (Input.GetMouseButtonDown (0)) {
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        RaycastHit2D[] hits = Physics2D.GetRayIntersectionAll (ray, Mathf.Infinity);
        foreach (var hit in hits) {
            if (hit.collider.name == name) {
                MyFunction ();
            }
        }
    }
}

2nd Case - If there is only 1 GameObject, and you try to understand if it is clicked:

void Update ()
{
    if (Input.GetMouseButtonDown (0)) {
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        RaycastHit2D hit = Physics2D.GetRayIntersection (ray, Mathf.Infinity);
        if (hit.collider != null && hit.collider.name == name) {
            MyFunction ();
        }
    }
}
like image 192
Ahmet Hayrullahoglu Avatar answered Oct 13 '22 08:10

Ahmet Hayrullahoglu