【问题标题】:How to change location of spawned instances without ruining instances' positions relative to each other?如何在不破坏实例相对位置的情况下更改生成实例的位置?
【发布时间】:2023-03-11 06:22:01
【问题描述】:

目前我的代码可以将一堆 Sphere 网格实例生成为 Cube 的形状(通过每个 Cube 网格的顶点生成一个 Sphere),如下所示:

public CubeMesh CubeMesh;
mesh = CubeMesh.GetComponent<MeshFilter>().mesh;

public GameObject spherePrefab;
public GameObject[] spheres;

public List<TransformData> matrices1 = new List<TransformData>();
Vector3[] matrices1pos = new Vector3[24]; //cube has 24 vertices

spheres = new GameObject[mesh.vertexCount]; 
for (int i = 0; i < mesh.vertexCount; i++)
{
    matrices1pos[i] = matrices1[i].position;
    spheres[i] = Instantiate(spherePrefab, matrices1[i].position, Quaternion.identity);
}

所以当你点击播放时,这可以让一堆球体实例创建一个立方体的形状。

我现在要做的是移动构成这个立方体形状的球体,这样这个“立方体”形状就可以跟随玩家,而不会破坏形状。

当我操作运行上述脚本的游戏对象的变换数据时,球体实例根本不会改变它们的位置。他们不关心 GameObject 的位置。

我也尝试将其作为另一个对象的父对象并移动父对象的位置,但球体实例位置也不关心父对象的位置。

在不改变实际球体相对于彼此的位置的情况下移动“立方体”形状的正确方法是什么?长这样(https://i.imgur.com/aGi4cOS.png),供参考。

编辑:

改为这样做:

spheres[i] = Instantiate(spherePrefab, matrices1[i].position, Quaternion.identity, transform);

允许我操纵球体实例的旋转和缩放,但不能操纵位置

Edit2:已解决!看看下面的答案

【问题讨论】:

  • spherePrefab 是纯模型数据还是附加了任何其他组件?您应该能够简单地将它们全部生成为一个 GameObject 的子对象,然后单独转换该公共父对象而不是每个球体……在您的屏幕截图中,所有球体实例都在根级别而不是在一个父对象之下。

标签: c# unity3d position transform


【解决方案1】:

我想通了!我需要使用本地位置。谢谢! =]

spheres[i].transform.SetParent(GO2.transform);
spheres[i].transform.localPosition = Vector3.Lerp(matrices1pos[i], matrices2[i].position, t);

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2023-01-27
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2014-12-11
    • 2013-11-19
    相关资源
    最近更新 更多