raycast wont hit collider after using NGUI?

早过忘川 提交于 2019-12-13 07:35:56

问题


after turn the main UI framework to NGUI, we found that We couldn't hit object with collider anymore with following code which was working fine we not using NGUI:

private void checkRayCast()
    {
        if ((Input.GetMouseButtonDown(0)))

        {

            Debug.Log("shoot ray!!!");

            Vector2 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit2;

            if (Physics.Raycast(ray, out hit2, 100))
            {

                //this should hit a 3d collider
                Debug.Log("we may hit something");
                Debug.Log(hit2.collider.gameObject.tag);
            }

            RaycastHit2D[] hits = Physics2D.RaycastAll(point, Vector2.zero, 0f);
            if (hits.Length != 0)
            {
                //this should all 2d collider
                Debug.Log(" ohh, we hit something");

            }
            else
            {
                Debug.Log("you hit nothing john snow!!!");
            }
            //if (hit.transform.gameObject.GetComponent<Rigidbody2D>() != null)
            //{

            //}
        }

    }

And we found that we could not hit a 2d collider or 3d collider anymore

Here is the target object's inspector:

EDIT

After following @programmer 's advice and resize the collider to a very big one, hit was detected(thanks, @programmer)

But the collider was changed to so big that it not event make scene. And We should find how big this should be now.

  • before resizing the collider in the scene note the green border which indicts the collider size made scene

  • here is the one that the collider works, but should be unreasonably large:


回答1:


After digging around And I have figured this out:

The trick is we should use UICamera.currentCamera instead of Camera.main to shoot the ray when we using NGUI.

If we click here in the game view to shoot the ray:

And If we add a line like:

Debug.DrawLine(ray.origin, ray.origin + ray.direction * 100, Color.red, 2, true);

After

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

We should see the actual ray in the scene in a 3d mode:

Note the red line which represents the ray and It could not shoot at the desired position since Camera.main have a different scale.

But if we change the carmera to UICamera to shoot the ray, We could shoot the ray that was desired.

Ray ray = UICamera.currentCamera.ScreenPointToRay(Input.mousePosition);

Hope this could help guys meet with the same pit.



来源:https://stackoverflow.com/questions/44579727/raycast-wont-hit-collider-after-using-ngui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!