码迷,mamicode.com
首页 > 编程语言 > 详细

unity3d点击屏幕选中物体

时间:2016-06-17 19:26:06      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

前些天接触unity3d,想实现点击屏幕选中物体的功能。后来研究了下,实现原理就是检测从屏幕发出的射线与物体发生碰撞,而这个发生碰撞的物体就是你选中的物体。

void MobilePick()
{
  if (Input.touchCount != 1 )
    return;

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

    if (Physics.Raycast(ray, out hit))
    {
      Debug.Log(hit.transform.name);
      //Debug.Log(hit.transform.tag);
    }
  }
}

void MousePick()
{
  if(Input.GetMouseButtonUp(0))
  {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit))
    {
      Debug.Log(hit.transform.name);
      //Debug.Log(hit.transform.tag);
    }
  }
}

在unity3d中,选中物体还有一个条件,就是物体能发生碰撞。这个参数就是碰撞器Collider,Collider是发生物理碰撞的基本条件。

所以如果无法选中物体时,要检查是否物体加了碰撞器。

方法如下:

GameObject gameObject = (GameObject)Instantiate(...);

gameObject.name = "game_object";
gameObject.AddComponent<MeshCollider>();
 

unity3d点击屏幕选中物体

标签:

原文地址:http://www.cnblogs.com/czaoth/p/5594759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!