使用parent移动gameObject以面对另一个gameObject

时间:2017-06-04 19:50:31

标签: unity3d

我有GameObject A,B,C。B是A的孩子.B和C是立方体,一边突出显示。

我想移动并旋转B和他的父A以将B的突出显示的一侧粘贴到C对象的突出显示的一侧。

怎么做?

1 个答案:

答案 0 :(得分:1)

我假设您只想更改A的值,以便B位置相对于A保持不变。

简单的解决方案是创建一个C对象的虚拟对象(使其变换相对于C),将其设置为您想要A的正确位置和旋转(突出显示的边粘贴),然后在运行时,你总是可以通过将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;
}
相关问题