I am writing a short script in c# to create a cube in unity. Everything is working fine up until I mess up all the cube points and things.
private Vector3[] GenerateVerts()
{
return new Vector3[]
{
// bottom x y z
new Vector3( 1, -1, -1),
new Vector3( 1, 1, -1),
new Vector3(-1, 1, -1),
new Vector3(-1, -1, -1),
// top
new Vector3( 1, -1, 1),
new Vector3( 1, 1, 1),
new Vector3(-1, 1, 1),
new Vector3(-1, -1, 1),
// left
new Vector3(-1, -1, 1),
new Vector3(-1, -1, -1),
new Vector3(-1, 1, 1),
new Vector3(-1, 1, -1),
// right
new Vector3( 1, -1, 1),
new Vector3( 1, -1, -1),
new Vector3( 1, 1, 1),
new Vector3( 1, 1, -1),
// front
new Vector3( 1, -1, -1),
new Vector3(-1, -1, -1),
new Vector3( 1, 1, -1),
new Vector3(-1, 1, -1),
// back
new Vector3( 1, -1, 1),
new Vector3(-1, -1, 1),
new Vector3( 1, 1, 1),
new Vector3(-1, 1, 1),
};
}
private int[] GenerateTris()
{
return new int[]
{
//bottom
0,1,2,
0,2,3,
//top
4,5,6,
4,6,7,
9,10,11,
8,10,9,
12,13,15,
14,12,15,
16,17,19,
18,16,19,
21,22,23,
22,20,23
};
}
I am very confused and am finding it hard to line everything up, put i t that way.
All of the sides are workin gfine then the top and bottom either overlap or appear where another face goes:
First of all as already hinted out in this answer your vertices are not correct. For instance "bottom" and "front" list the very same vertices just in different order. Same as with "back" and "top"
=> What you get is missing bottom and top faces but partially double-side rendered right and left so I would claim these two minimum you want to review.
However, in general it is rather unusual to list the same vertices multiple times - except you really require all faces to use individual vertices (for example in order to detach them from another).
You usually want to list all vertices only once and then re-use the vertex in multiple triangles.
=> A cube actually requires only 8
vertices like e.g.
private readonly Vector3[] Verts = new []
{
// front-face, clockwise, starts bottom left
new Vector3(-1, -1, -1),
new Vector3(-1, 1, -1),
new Vector3( 1, 1, -1),
new Vector3( 1, -1, -1),
// back face, clockwise, starts bottom left
new Vector3(-1, -1, 1),
new Vector3(-1, 1, 1),
new Vector3( 1, 1, 1),
new Vector3( 1, -1, 1),
};
And then you rather reference the according vertices in multiple faces (triangles). Here you have to have the winding-order in mind!
Unity uses clockwise winding order meaning if you look onto a triangle and its vertices are in counter-clockwise order, you are looking at the back of that triangle.
By default most of shaders apply backface culling, meaning triangles you are seeing from mentioned "behind" are not rendered.
so in order to always have the triangles to point outwards away from the cube => make them visible from the outside it would be e.g.
private int[] GenerateTris()
{
return new int[]
{
// front
0,1,2,
0,2,3,
// top
1,5,6,
1,6,2,
// right
2,6,3,
3,6,7,
// left
1,4,5,
0,4,1,
// bottom
0,7,4,
0,3,7,
// back
4,7,6,
4,6,5
};
}