zoukankan      html  css  js  c++  java
  • unity3d点击屏幕选中物体

    前些天接触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>();
     
  • 相关阅读:
    10.30 afternoon
    10.29 afternoon
    10.29 morning

    10.27 noip模拟试题
    codevs 3052 多米诺 二分图匹配
    poj 1849 Two
    10.26 noip模拟试题
    10.25 noip模拟试题
    .NET Core EF 版本问题
  • 原文地址:https://www.cnblogs.com/czaoth/p/5594759.html
Copyright © 2011-2022 走看看