简体   繁体   中英

Draw Spheres on Vertex of a cube in Unity

I'm quite new to Unity here and I have been trying to draw a couple of spheres on the vertex of a Cube gameobject. The code is as follows

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

The problem here is that the spheres occur somewhere else in world space and not on the vertices of the Cube. I think I am going wrong somewhere in transform.position. Any help would be appreciated.

The problem is that the positions of the vertices are in local space. All you need to do is to transform the positions into world-space like so:

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

Then you can implement this into your code like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM