如何在不添加对象的情况下找出相对于父项的局部坐标?统一

How to find out local coordinates relative to the parent without adding an object to it? Unity

提问人:Operator 提问时间:11/1/2023 更新时间:11/1/2023 访问量:33

问:

我正在向父级添加一个对象:

Transform target = Instantiate(_leftTargetPrefab, leftTargetPosition, Quaternion.identity);
target.SetParent(_ballsParent, false);

我正在尝试获取父级内部的坐标,但它们不匹配:

Vector3 testPos = _ballsParent.InverseTransformPoint(leftTargetPosition);

是否可以在不添加对象的情况下找出父项内部的坐标?

unity-game-engine 矢量 位置 实例化

评论

0赞 hijinxbassist 11/2/2023
I'm trying to get the coordinates inside the parent, but they don't match:如果要与检查器位置值进行比较,请确保相关对象不是父级,否则将查看本地位置。InverseTransformPoint 应该是正确答案。此外,请确保在函数中使用世界位置。

答:

1赞 The Ash Bot 11/1/2023 #1

要获取相对于父项的坐标,可以通过父项的世界位置减去坐标。

Vector3 relativeCoordinates = coordinates - transform.parent.position;

要获取子项相对于父项的位置,可以使用而不是transform.localPositiontransform.position

0赞 Soul 11/1/2023 #2

我不确定我是否正确。但是,如果您正在寻找子对象的位置,请尝试以下操作:

var localPosition = _ballsParent.transform.Find("ChildName").transform.localPosition;

顺便说一句,“The Ash Bot”的答案比通过名称查找游戏对象要好:P