Convert 3D Raycast to Raycast2D

不羁岁月 提交于 2019-12-01 14:25:30

use RaycastHit2D to do this instead of RaycastHit then change Physics.Raycast to Physics2D.Raycast. The parameters are different the code below should do it.You may also have to change && to || depending on your game logic.

Select the Sprite then add Box Colider 2D from the Editor. You can also use Circle Collider 2D for the Sprite if your Sprite is round. If you don't add any 2D collider to the Sprite, ray won't detect the object when clicked on.

FOR MOBILE DEVICES

if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
  {
            Vector2 cubeRay = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            RaycastHit2D cubeHit = Physics2D.Raycast(cubeRay, Vector2.zero);
            if (cubeHit)
            {
                //We hit something
                Debug.Log(cubeHit.transform.gameObject.name);
                if (this.target != null)
                {
                    SelectMove sm = this.target.GetComponent<SelectMove>();
                    if (sm != null) { sm.enabled = false; }
                }
                target = cubeHit.transform.gameObject;
                //Destroy(cubeHit.transform.gameObject);
                selectedPlayer();
            }
  }

FOR DESKTOPS / EDITOR

if (Input.GetMouseButtonDown(0))
        {
            Vector2 cubeRay = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D cubeHit = Physics2D.Raycast(cubeRay, Vector2.zero);
            if (cubeHit)
            {
                //We hit something
                Debug.Log(cubeHit.transform.gameObject.name);
                if (this.target != null)
                {
                    SelectMove sm = this.target.GetComponent<SelectMove>();
                    if (sm != null) { sm.enabled = false; }
                }
                target = cubeHit.transform.gameObject;
                //Destroy(cubeHit.transform.gameObject);
                selectedPlayer();
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!