在 Unity 立方体的顶点上绘制球体

Draw Spheres on Vertex of a cube in Unity

我是 Unity 的新手,我一直在尝试在 Cube 游戏对象的顶点上绘制几个球体。代码如下

public GameObject Elements;
 public float gapWidth = 0.01f;

void Start()
{Elements = GameObject.CreatePrimitive(PrimitiveType.Cube);
        Elements.name = "Ele1";
        Elements.transform.position = new Vector3(0.0f * gapWidth + 0.5f, 0.0f * gapWidth + 0.5f, 0.0f * gapWidth + 0.5f);
        Elements.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
Vector3[] vertices = Elements.GetComponent<MeshFilter>().mesh.vertices;

GameObject[] Spheres = new GameObject[vertics.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            Spheres[i] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            Spheres[i].transform.position = vertices[i];
            Spheres[i].transform.localScale -= new Vector3(0.8F, 0.8F, 0.8F);
        }
}

这里的问题是球体出现在世界的其他地方 space 而不是在立方体的顶点上。我想我在 transform.position 的某处出错了。 任何帮助将不胜感激。

问题是顶点的位置在局部space。您需要做的就是将位置转换为 world-space,如下所示:

Matrix 4x4 localToWorld = transform.localToWorldMatrix;

Vector3[] localSpaceVerts = Elements.GetComponent<MeshFilter>().mesh.vertices;
Vector3[] worldSpaceVerts = new Vector3[localSpaceVerts.Lenght];

for(int i = 0; i < localSpaceVerts.Length; ++i){
   worldSpaceVerts[i] = localToWorld.MultiplyPoint3x4(localSpaceVerts[i]);
}

然后您可以像这样将其实现到您的代码中:

public GameObject Elements;
public float gapWidth = 0.01f;
void Start(){

Matrix 4x4 localToWorld = transform.localToWorldMatrix;

Elements = GameObject.CreatePrimitive(PrimitiveType.Cube);
Elements.name = "Ele1";
Elements.transform.position = new Vector3(0.0f * gapWidth + 0.5f, 0.0f *
gapWidth + 0.5f, 0.0f * gapWidth + 0.5f);
    Elements.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
Vector3[] vertices = Elements.GetComponent<MeshFilter>().mesh.vertices;
GameObject[] Spheres = new GameObject[vertics.Length];
for (int i = 0; i < vertices.Length; i++){
    Spheres[i] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
    Spheres[i].transform.position = localToWorld.MultiplyPoint3x4(vertices[i]);
    Spheres[i].transform.localScale -= new Vector3(0.8F, 0.8F, 0.8F);
}
}