c# - unity设置父对象位置等于它们的子位置
问题描述
我有两个 3D 对象,最终它们将是不同大小和形状的 3D 模型,但我正在努力使底层功能正确。
一个是常规 Sphere,其子游戏对象位于 (0,-0.5,0) 位置,名为 s1。
一个是缩放的圆柱体 (0.3,0.3,0.3),其子游戏对象位于 (0,0.5,0) 位置,名为 c1。
我正在尝试移动对象,以便两个父对象在同一个子对象位置对齐。
下面的代码将圆柱体位置直接移动到 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;
}
解决方案
虽然您的问题不是很清楚,但我认为您的意思是您正在尝试定位圆柱体和球体,使其子对象(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;
推荐阅读
- python - cx_Freeze 缺少模块
- database - Symfony4 具有相同结构的多个数据库
- python - 获取像素位置
- javascript - 使用扩展运算符的 ES6 对象克隆也在修改输入
- javascript - 使用 mousemove 事件转换 jQuery 眼瞳跟踪器
- node.js - 如何在 Ubuntu 18.10 中安装 Node Js?
- jqgrid - JQGrid 本地搜索多列
- c# - “您的意思是运行 dotnet SDK 命令吗?请在 Windows 命令提示符下安装 dotnetsdk”
- python - 通过蓝牙将音乐从带有 Ubuntu 的 PC 流式传输到音频设备
- c - 将自动变量的指针传递给 DMA 函数