【问题标题】:Moving gameObject with parent to face another gameObject将游戏对象与父对象一起移动以面对另一个游戏对象
【发布时间】:2017-06-05 18:12:35
【问题描述】:

我有游戏对象 A、B、C。B 是 A 的子对象。B 和 C 是一侧突出显示的立方体。

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

如何做到这一点?

【问题讨论】:

  • 你能告诉我们你自己试过的代码吗?

标签: unity3d


【解决方案1】:

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

简单的解决方案是创建一个虚拟对象,它是 C 的子对象(使其变换相对于 C),将其设置为您希望 A 成为的正确位置和旋转(突出显示的边粘贴的位置),然后在运行时,您总是可以通过将 A 的位置和旋转设置为与假人相同的方式将 A 移动到该位置。由于 dummy 的变换是相对于 C 的,所以无论您如何更改 C 的变换,dummy 将始终保持在正确的位置并为您提供正确的 A 值。

另一个解决方案是数学。但是,我认为使用复杂的计算函数不会那么有效(对于计算机和你的头脑来说,哈哈)。使用虚拟对象会更好,因为 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    相关资源
    最近更新 更多