【发布时间】:2020-05-20 01:54:44
【问题描述】:
这里是新手。我想将一个 GameObject 实例化到父级的特定位置。我想把它放在父母的顶部。我可以在实例化它时立即定位它还是需要使用 transform.position?在任何一种情况下,我都不知道该怎么做。如果您对自己的时间感到慷慨,我还需要弄清楚如何在父母身上轮换孩子。此外,每个子/副本或新实例化对象都将随着每次新迭代而缩放。我正在尝试构建一棵反向分形树(随着时间的推移,树枝会变大)。
只是一个警告 - 您可能会对代码中可能写得更好的其他部分感到畏缩。
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Transform Cube;
public GameObject masterTree;
public int instanceCounter = 1;
public int numCubes = 30;
public float scalar = 1.4145f;
public float initialScale = 10f;
public float angle = 30f;
private Transform copy;
void Start()
{
}
private void Update()
{
if (instanceCounter <= numCubes)
{
if (instanceCounter == 1)
{
copy = Instantiate(Cube, new Vector3(0, 0, 0), Quaternion.identity);
copy.transform.localScale = new Vector3(1f, initialScale, 1f);
copy.name = "Copy" + instanceCounter;
copy.transform.parent = masterTree.transform;
instanceCounter++;
}
var copyParent = GameObject.Find("Copy" + (instanceCounter - 1));
Vector3 copyParentSize = copyParent.GetComponent<Renderer>().bounds.size;
Debug.Log("copyParentSizeY = " + copyParentSize.y);
copy = Instantiate(Cube, new Vector3(0, 0, 0), Quaternion.identity);
copy.transform.localScale = new Vector3(1f, initialScale, 1f);
initialScale = initialScale * scalar;
copy.name = "Copy" + instanceCounter;
//copy.transform.rotation *= Quaternion.Euler(angle, angle, 0);
copy.transform.parent = copyParent.transform;
instanceCounter++;
}
}
}
【问题讨论】:
-
I want to place it at the top of the parent.你到底是什么意思?到父对象的相同位置或上方?另外,I also need to figure out how to rotate the child on the parent到底是什么意思?您能否添加所需结果的图片.. 有点难以想象。由于您是对象的父对象,因此您可以简单地将它们的transform.localPosition和transform.localRotation与所需的偏移量分配给相应的父对象 -
感谢 derHugo 澄清问题!当我说我想把它放在父级的顶部时,我的意思是,如果父级是一个高圆柱体,我想把子级堆叠在圆柱体的顶部,就像一个个堆叠在一起的盒子一样。至于旋转,我希望能够在父母和孩子连接的那个“连接点”上旋转孩子。我认为 transform.localPosition 和 transform.localRotation 是要走的路,我似乎无法理解它们在代码中的确切工作方式。
-
如前所述,我认为说明您的预期结果将如何(绘画、统一放置的正确放置对象的屏幕截图等)确实有助于弄清楚您的需求究竟是什么
-
我似乎需要更多的积分来添加图像。这是我要完成的工作的链接:jonathangibson.com/unity/moving.png我希望能够在有和没有父母的情况下做到这一点。
-
这是一个视频,展示了当我将对象彼此作为父对象时得到的结果:jonathangibson.com/unity/unity2.m4v 我正在使用 copy.transform.localPosition = new Vector3(0, 1.5F, 0);改变他们的立场。孩子之间的间距不精确。我认为这是因为缩放?我也不明白铰链点是如何工作的。
标签: unity3d position parent-child parent children