Home > database >  Draw Spheres on Vertex of a cube in Unity
Draw Spheres on Vertex of a cube in Unity

Time:02-02

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.

CodePudding user response:

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);
}
}
  •  Tags:  
  • Related