1. 程式人生 > >unity3d點選螢幕選中物體

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