统一设置 Parent Objects position 等于 Their child position

Unity Setting Parent Objects position Equal to Their child position

我有两个 3D objects 最终它们将是不同大小和形状的 3D 模型,但我正在努力使底层功能正确。

一个是一个规则的球体,在位置 (0,-0.5,0) 有一个 child 游戏对象,名为 s1。

一个是一个缩放比例为 (0.3,0.3,0.3) 的圆柱体,在位置 (0,0.5,0) 的 child 游戏对象名为 c1。

我正在尝试移动 object,使两个 parents 对齐在相同的 child object 位置。

下面的代码将柱面位置直接移动到s1位置。我只是无法计算矢量数学,所以 c1 位置直接在 s1 位置上。我尝试了多种不同的加法、减法、除法来使它们对齐,但没有任何运气。任何帮助理解如何解决这个问题的人都将不胜感激。

public GameObject sphere;
public GameObject cyclinder;

private GameObject s1;
private GameObject c1;

// Start is called before the first frame update
void Start()
{
    s1 = sphere.transform.Find("s1").gameObject;
    c1 = cyclinder.transform.Find("c1").gameObject;


    cyclinder.transform.position = s1.transform.position;
}

这个问题的答案是

cyclinder.transform.position = s1.transform.position - (c1.transform.localposition/4);

虽然您的问题不是很清楚,但我认为您的意思是您正在尝试定位圆柱体和球体,使其子对象(s1 和 c1)共享完全相同的世界位置。

我要遵循的步骤是:

  • 计算子对象与其父对象之间的 world-space 偏移量(通常这只是子对象的 localPosition,但由于您还应用了 localScale,因此通过手动计算使用世界位置的偏移向量)
  • 设置父位置为新位置+上述偏移量

例如:

Vector3 finalPos = ... // Position I want both s1 and c1 to share

// Cylinder: world offset, moving from c1 to the parent object
Vector3 cylOffset = cylinder.transform.position - c1.transform.position;

// Position the cylinder, and apply the offset
cylinder.transform.position = finalPos + cylOffset;

// Sphere: world offset, moving from s1 to the parent object
Vector3 sphereOffset = sphere.transform.position - s1.transform.position;

// Position the sphere, and apply the offset
sphere.transform.position = finalPos + sphereOffset;