我目前正在开发游戏引擎,并被要求制作一种方法,该方法采用一个顶点数组并输出一个float数组。我们有一个针对Vector3的类。 Vector3是3个浮点数x,y和z的包装。顶点只是Vector3f的包装。因此,如果它们是一个顶点数组,我如何将其转换为浮点数组。这是我到目前为止所拥有的
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;
}
期望的输出将被放置在顶点数组中以形成一个正方形,例如
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
}
你会得到
{0.5f,-0.5f,0,-0.5f,0.5f,0,0.5f,0.5f,0 ,-0.5f,-0.5f,0}
结果
答案 0 :(得分:0)
1。在您的示例中,您正在创建一个数组,该数组的大小与输入的顶点数相同,但是由于每个顶点都有3个浮点数,因此您想创建一个数组,其数组的大小为输入的三倍
float[] floats = new float[vertices.length*3];
2。然后,您正确地执行了for循环,但从未更改索引i
。
这意味着您仅覆盖索引0,1和2。
取而代之的是,您需要在每个循环中将i
加3(您要在i
,i+1
和i+2
上添加
类似这样的东西:
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;
i+=3;
}
或者您可以使用i++
将i
加1并返回i
的值之前
如果再结合这两个建议,我们会得到
public static float[] VertexArrayToFloatArray(Vertex[] vertices){
float[] floats = new float[vertices.length*3];
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++] = y;
floats[i++] = z;
}
System.out.println(floats);
return floats;
}