2017-06-20 75 views
-3

我正在使用Unity的Vector3方法,ScreenToWorldPoint統一獲取單擊事件向量

總之,我可以點擊一個遊戲對象的任何地方,並獲得點擊在遊戲中的Vector3。但是我得到的結果是直接在相機前面的Vector3,而不是真正點擊場景中給定GameObject表面的地方。

我想要的是我在GameObject表面上點擊的座標。

回答

2

你想從相機到物體的Raycast。有關詳情,請Manual: Rays from the camera

using UnityEngine; 
using System.Collections; 

public class ExampleScript : MonoBehaviour { 
    public Camera camera; 

    void Start(){ 
     RaycastHit hit; 
     Ray ray = camera.ScreenPointToRay(Input.mousePosition); 

     if (Physics.Raycast(ray, out hit)) { 
      Transform objectHit = hit.transform; 

      // Do something with the object that was hit by the raycast. 
     } 
    } 
} 
+0

是的,我對ScreenToWorldPoint進行了精確設置。我需要的是ScreenPointToRay。在我的情況下,我需要的載體是hit.point。對於那些不知道hit.point是什麼的人來說,hit.point是射線擊中對撞機的確切點(表示爲Vector3())(或者在我的情況下,鼠標點擊對撞機的位置)。感謝您的幫助! – jtth

0

幫助頁面要獲得完全的Vector3,你一個遊戲物體的表面上點擊使用下面的代碼:

RaycastHit hit; 
    Ray ray; 
    Camera c = Camera.main; 
    Vector3 hitPoint; 


    Rect screenRect = new Rect(0, 0, Screen.width, Screen.height); 
    if (screenRect.Contains(Input.mousePosition)) 
    { 
     if (c != null) 
     { 
      ray = c.ScreenPointToRay(Input.mousePosition); 

      if (Physics.Raycast(ray, out hit)) 
      { 
       // If the raycast hit a GameObject... 
       hitPoint = hit.point; //this is the point we want 
      } 

     } 
    } 

我們從屏幕上的鼠標創建射線並將其投射到世界中以計算鼠標在場景中的確切位置。