I am currently developing a game engine, and was asked to make a method that takes in a vertex array and outputs a float array. We have a class made for Vector3. Vector3 is a wrapper for 3 floats, x,y and z. The vertex is just a wrapper for a Vector3f. So if their is a vertex array how can i turn it into a float array. This is what i have so far
public static float[] VertexArrayToFloatArray(Vertex[] vertices){
float[] floats = new float[vertices.length];
int i = 0;
for (Vertex v : vertices){
float x, y, z;
x = v.getPosition().getX();
y = v.getPosition().getY();
z = v.getPosition().getZ();
floats[i] = x;
floats[i + 1] = y;
floats[i + 2] = z;
}
System.out.println(floats);
return floats;
}
An expected output would be puting in a vertex array to make a square such as
Vertex[] vertices = new Vertex[]{
new Vertex(new Vector3f(0.5f,-0.5f,0)), //Bottom Right
new Vertex(new Vector3f(-0.5f,0.5f,0)), // Top Left
new Vertex(new Vector3f(0.5f,0.5f,0)), //Top Right
new Vertex(new Vector3f(-0.5f,-0.5f,0)) //Bottom Left
}
and you would get
{0.5f,-0.5f,0,-0.5f,0.5f,0,0.5f,0.5f,0 ,-0.5f,-0.5f,0}
as the result
1. In your example, you are creating an array with the size of the number of vertices from the input, but since every Vertex has 3 floats you want to create an array with triple the size of the input
2. Then you are correctly doing for loop but you are never changing the index
i.That means that you are only overwriting index 0,1 and 2.
Instead of that, you need to increment the
iby 3 (You are adding oni,i+1, andi+2) every loopSomething like this:
Or you can use
i++which increaseiby 1 and returns the value ofiBEFORE increasing If we then combine those 2 advise we get