首页 > 解决方案 > 如何在不破坏实例相对位置的情况下更改生成实例的位置?

问题描述

目前,我有将一堆球体网格实例生成为立方体形状的代码(通过为每个立方体网格的顶点生成一个球体),如下所示:

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);

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

编辑2:解决了!请看下面的答案

标签: c#unity3dpositiontransform

解决方案


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

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

推荐阅读