2017-04-18 97 views
0

我有一個攝像頭,它將userInterface(畫布)對象顯示在我的相機前面。 我只更新我的用戶界面位置,如果相機光線不擊中我的userInterface對象對撞機。像這樣旋轉相機時對象旋轉不正確

public class UIPlacerAtCamFront : MonoBehaviour { 

    public GameObject userInterface; 
    public float placementDistance; 
    Vector3 uiPlacementPosition; 
    RaycastHit objectHit; 

    void Update() { 

     Vector3 fwd = this.transform.TransformDirection(Vector3.forward); 
     //Debug.DrawRay(this.transform.position, fwd * 50, Color.green); 

     if (Physics.Raycast(this.transform.position, fwd, out objectHit, 50)) 
     { 
      //raycast hitting the userInterface collider, so do nothing, userinterface is infornt of the camrea already 
     } 
     else 
     { 
      //raycast is not hitting userInterfae collider, so update UserInterface position accoding to the camera 
      uiPlacementPosition = this.transform.position + this.transform.forward * placementDistance; 
      userInterface.transform.position = uiPlacementPosition; 
     } 

     //Continuously update userInterface rotation according to camera 
     userInterface.transform.rotation = this.transform.rotation; 
    } 
} 

上述腳本已附有我的相機,它正確顯示的對象,但我開始轉動我的相機我的UI對象的旋轉看起來如下圖像建議 This is inital correct rotation

非常奇怪我旋轉,就會出現此問題 enter image description here

我知道問題出在旋轉,所以我累了改變我的這個輪換代碼

userInterface.transform.rotation = this.transform.rotation; 

這個

userInterface.transform.localEulerAngles = new Vector3 (this.transform.localEulerAngles.x, 
      0, 
      this.transform.localEulerAngles.z); 

,但它帶來的另一個陌生的旋轉對我來說就像下面 enter image description here

我想,我的userinteface對象面對我的相機correclty,甚至我的相機看開頭或結尾給出我的用戶界面對象。如何根據相機旋轉正確旋轉我的用戶界面?

+0

我建議設置渲染模式畫布成'屏幕空間上 - Overlay'。 – Iggy

+0

我不確定期望的行爲會是什麼(在第二張圖片上)。你介意一點點介紹一下嗎? 另外...如果你有歐拉角度的問題嘗試'Quaternion.LookAt()',我覺得它更直觀和防彈。 –

+0

@lggy我不能讓它的屏幕空間 –

回答

0

如果我理解正確的話。你想要一個類似於滑動谷歌地圖的行爲。只有相機必須旋轉並且圖片必須調整其行爲的位置和旋轉角度。

下面的代碼應該這樣做:

void Update() { 
    userInterface.transform.rotation = this.transform.rotation; 

    // Project camera to canvas plane 
    Vector3 projection = Vector3.ProjectOnPlane(this.transform.position - userInterface.transform.position, userInterface.transform.forward) 
     + userInterface.transform.position; 

    // Get distance from camera to projected position (basically, distance from point to plane) 
    float curDistance = (this.transform.position - projection).magnitude; 

    // Correct that distance with desired distance 
    userInterface.transform.position += this.transform.forward * (placementDistance - curDistance); 
} 
+0

我只是想更新用戶界面的位置,如果光線投射是不打userinteface。因爲我正在從我的相機進行一些選擇到用戶界面 –

+0

相機包含一個在用戶界面上選擇不同對象的子指針,它會旋轉以在畫布的不同位置進行選擇。如果我更新所有時間位置作爲您的代碼建議我將無法選擇它 –

+0

您可以保存旋轉,而不是位置。或者你可以使用第二臺相機將平面邏輯上的ui渲染到頂端,但我沒有看到如何保持與旋轉物體的恆定最小距離而不會稍微移位它。 –