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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM