Unity 2D射线与 3D射线 UI射线

//3D射线 
if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从摄像机发出到点击坐标的射线
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                Debug.DrawLine(ray.origin, hitInfo.point);//划出射线,只有在scene视图中才能看到
                GameObject gameObj = hitInfo.collider.gameObject;
                Debug.Log("click object name is " + gameObj.name);
            }
        }


//2D射线

        RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition),Vector2.zero);
        if(hit.collider != null)
        {
            Debug.Log("Target Position: " + hit.collider.gameObject.name);
        }





2D射线只会碰撞到      Submarine  层

 RaycastHit2D hit = Physics2D.Raycast(worldpos, Vector2.zero, 100, 1 << LayerMask.NameToLayer("Submarine"));


//UI射线

public void OnDrag (PointerEventData eventData) {
		transform.position = Camera.main.ScreenToWorldPoint(eventData.position);
		GraphicRaycaster gr = GetComponentInParent ().GetComponent ();
		List results = new List ();

		gr.Raycast (eventData, results);

		foreach (RaycastResult result in results) {
			Debug.Log (result.gameObject.name);
		}

	}



你可能感兴趣的:(unity)