Unity 版本:4.5 NGUI版本:3.6.5
參考鏈接:http://game.ceeger.com/Script/Camera/Camera.ScreenPointToRay.html,Uniyt聖典
http://www.unitymanual.com/blog-4392-1229.html,作者:游戲蠻牛 han1127
http://www.cnblogs.com/alongu3d/archive/2013/01/05/raycast1.html,博客園 夢想之家
1、3D物體的點擊事件響應:
下述代碼添加到3D 物體中,通過對鼠標點擊位置的射線進行碰撞檢測,然后判斷點擊的是不是當前的對象即可
void Update() { if (Input.GetButtonDown("Fire1")) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if (hit.collider.gameObject == gameObject) { //插入執行代碼 } } } }
2、世界坐標轉為NGUI坐標:
// 獲取目標物體的屏幕坐標 Vector3 pos = Camera.main.WorldToScreenPoint(gameobject); // 將屏幕坐標轉換為UI的世界坐標 pos = UICamera.currentCamera.ScreenToWorldPoint(pos); // 由於NGUI 2D界面的Z軸都為0 pos.z = 0; // 將修改過的坐標賦給UI界面 _button.transform.position = new Vector3(pos.x, pos.y, pos.z);
3、NGUI坐標轉為世界坐標:
// 獲取按鈕的屏幕坐標 Vector3 pos = UICamera.currentCamera.WorldToScreenPoint(_button.transform.position); pos.z = 1; pos = Camera.main.ScreenToWorldPoint(pos); _cube.transform.position = new Vector3(pos.x,pos.y,pos.z);