2017-06-04 103 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; 
} 
相关问题