纳金网

标题: 点击屏幕选中物体的代码(转载) [打印本页]

作者: 狂风大尉    时间: 2014-7-31 11:34
标题: 点击屏幕选中物体的代码(转载)
  1. void MobilePick()
  2. {
  3.   if (Input.touchCount != 1 )
  4.     return;

  5.   if (Input.GetTouch(0).phase == TouchPhase.Began)
  6.   {
  7.     RaycastHit hit;
  8.     Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

  9.     if (Physics.Raycast(ray, out hit))
  10.     {
  11.       Debug.Log(hit.transform.name);
  12.       //Debug.Log(hit.transform.tag);
  13.     }
  14.   }
  15. }

  16. void MousePick()
  17. {
  18.   if(Input.GetMouseButtonUp(0))
  19.   {
  20.     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  21.     RaycastHit hit;

  22.     if (Physics.Raycast(ray, out hit))
  23.     {
  24.       Debug.Log(hit.transform.name);
  25.       //Debug.Log(hit.transform.tag);
  26.     }
  27.   }
  28. }
复制代码
在unity3d中,选中物体还有一个条件,就是物体能发生碰撞。这个参数就是碰撞器Collider,Collider是发生物理碰撞的基本条件。
所以如果无法选中物体时,要检查是否物体加了碰撞器。
方法如下:
  1. GameObject gameObject = (GameObject)Instantiate(...);

  2. gameObject.name = "game_object";
  3. gameObject.AddComponent<MeshCollider>();
复制代码

作者: HIDEOKOJIMA    时间: 2014-7-31 11:39
Thanks for sharing this !
作者: 我不再年轻    时间: 2014-7-31 12:42
学习了, 多谢分享
作者: hyui    时间: 2014-7-31 19:11
Thanks for sharing !
作者: 嵐淵瑟    时间: 2014-10-16 16:16
支持一個,感謝分享~~




欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5