2017-06-04 102 views
0

我有GameObject A,B,C。B是A的孩子。B和C是一側突出顯示的立方體。將父對象移動到另一個遊戲對象

我想移動並旋轉B和他的父A,以將B的突出顯示的一面粘貼到C對象的突出顯示的一面。

如何做到這一點?

+0

你能告訴我們你自己試過的代碼嗎? –

回答

1

我以爲你只是想改變一個的值,使B地理位置保持相對A.完整

簡單的解決方案是創建一個虛擬對象,它是C的孩子(以使其轉化爲相對到C),將它設置到正確的位置和旋轉你想要A(突出顯示的兩邊粘住),然後在運行時你可以將A移動到該位置,方法是將它的位置和旋轉設置爲與假人相同。由於虛擬變換與C相關,無論您如何改變C的變換,虛擬將始終保持在正確的位置併爲您提供A的正確值。

另一個解決方案是Math。但是,我認爲使用複雜的計算函數不會那麼高效(對於計算機和你的頭像都是如此)。使用虛擬對象會更好,因爲Unity爲你做了數學運算,但它不涉及額外的計算。但也許它會是這樣的:

public Transform a; 
public Transform b; 
public Transform c; 

public Vector3 b_hl_dir; // highlight direction (e.g. right side would be {1,0,0} and back side would be {0,0,-1}) 
public Vector3 c_hl_dir; 

public float width; // cube's width, assuming b and c has the same width. 

public void RelocateA(){ 
    // #1. Calculate correct position for B 
    Vector3 b_pos = c.position + c.rotation * c_hl_dir * width; 
    Quaternion b_rot = Quaternion.LookRotation(c.position - b_pos, (Mathf.Abs(Vector3.Dot(c_hl_dir, Vector3.up)) < 1f) ? c.up : c.right) * Quaternion.FromToRotation(b_hl_dir, Vector3.forward); 

    // #2. Relocate A according to B's correct position 
    a.rotation = b_rot * Quaternion.Inverse(b.localRotation); 
    a.position += b_pos - b.position; 
} 
相關問題