C# 统一设置父对象的位置等于其子对象的位置
我有两个3D对象,最终它们将是不同大小和形状的3D模型,但我正在尝试正确使用底层功能 一个是一个规则球体,其子游戏对象位于(0,-0.5,0)位置,名为s1。 其中一个是一个圆柱体,按比例缩放(0.3,0.3,0.3),子游戏对象位于名为c1的位置(0,0.5,0)。 我正在尝试移动对象,以便两个父对象在同一子对象位置对齐 下面的代码直接在s1位置上移动cyclinder位置。我只是很难计算出向量数学,所以c1位置直接在s1位置上。我尝试了多种不同的加法、减法、除法,以使它们对齐,但没有任何运气。如果您能帮助理解如何解决此问题,我们将不胜感激C# 统一设置父对象的位置等于其子对象的位置,c#,unity3d,vector,parent-child,C#,Unity3d,Vector,Parent Child,我有两个3D对象,最终它们将是不同大小和形状的3D模型,但我正在尝试正确使用底层功能 一个是一个规则球体,其子游戏对象位于(0,-0.5,0)位置,名为s1。 其中一个是一个圆柱体,按比例缩放(0.3,0.3,0.3),子游戏对象位于名为c1的位置(0,0.5,0)。 我正在尝试移动对象,以便两个父对象在同一子对象位置对齐 下面的代码直接在s1位置上移动cyclinder位置。我只是很难计算出向量数学,所以c1位置直接在s1位置上。我尝试了多种不同的加法、减法、除法,以使它们对齐,但没有任何运气
答案是这样做
cyclinder.transform.position = s1.transform.position - (c1.transform.localposition/4);
虽然您的问题不是很清楚,但我认为您的意思是,您试图以这样一种方式来定位圆柱体和球体,即它们的子对象(s1和c1)共享完全相同的世界位置 我将遵循以下步骤:
- 计算子对象与其父对象之间的世界空间偏移(通常这只是子对象的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;
所以你想要opt1:(sphere.pos=s1.pos和c1.pos),opt2:(c1.pos=s1.pos和sphere.pos!=c1.pos)或者别的什么?我不太明白你想做什么.这背后有数学依据吗?还是只对你有用?
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;