//鼠标右键点击 if (Input.GetMouseButtonUp(1)) { // 点击鼠标左键抬起时发射一条射线 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo)) { Debug.Log("click object name is ---->" + hitInfo.collider.gameObject.name); }
//在半径为5的球形范围内的所有3d物体都会被检测到 Collider[] colliders = Physics.OverlapSphere(Vector3.zero, 5.0f); if (colliders.Length > 0) { for (int i = 0; i < colliders.Length; i++) { Debug.Log("第二种方式---click object name is ---->" + colliders[i].gameObject.name); } } }
//左 if (Input.GetMouseButtonUp(0)) { // 第一种方法,与3d检测类似 RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); if (hit.collider != null) { Debug.Log("clicked object name is ---->"+ hit.collider.gameObject); }
// 第二种方法,overlap检测物体重叠的点 Collider2D[] collider2Ds = Physics2D.OverlapPointAll(Camera.main.ScreenToWorldPoint(Input.mousePosition)); if (collider2Ds.Length > 0) { for (int i = 0; i < collider2Ds.Length; i++) { Debug.Log("overlap object point,The name is ---->" + collider2Ds[i].gameObject.name); }
//foreach (Collider2D item in collider2Ds) //{ // Debug.Log("overlap object point,The name is ---->" + collider2Ds[i].gameObject.name); //} } }