Raycasting to find mouseclick on Object in unity 2d games

前端 未结 4 1213
猫巷女王i
猫巷女王i 2021-02-04 13:10

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 () {

           


        
4条回答
  •  面向向阳花
    2021-02-04 14:03

    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 ();
            }
        }
    }
    

提交回复
热议问题