且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 3D Raycast 转换为 Raycast2D

更新时间:2023-11-17 13:48:58

使用 RaycastHit2D 来代替 RaycastHit 然后改变 Physics.Raycast> 到 Physics2D.Raycast.参数不同,下面的代码应该这样做.您可能还需要根据您的游戏逻辑将 && 更改为 ||.

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.

选择Sprite,然后从编辑器中添加Box Collider 2D.如果您的 Sprite 是圆形的,您还可以将 Circle Collider 2D 用于 Sprite.如果您不向 Sprite 添加任何 2D 碰撞器,则单击时光线将不会检测到该对象.

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.

对于移动设备

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

对于桌面/编辑器

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