简体   繁体   English

如何在OpenGL ES(iPhone)中批量渲染精灵

[英]How to batch render sprites in OpenGL ES (iPhone)

I have a game that renders a bunch of sprites (several hundred), almost all of which are using the same texture. 我有一个游戏,渲染一堆精灵(几百),几乎所有精灵都使用相同的纹理。 Currently, I'm calling glDrawArrays(...) for each one, which I recently discovered was very inefficient. 目前,我正在为每一个调用glDrawArrays(...),我最近发现这是非常低效的。 After doing some research, I've learned that I need to put all my vertices for every sprite into one big vertex buffer, and call glDrawArrays(...) just once using that. 在做了一些研究之后,我了解到我需要将每个精灵的所有顶点放入一个大的顶点缓冲区,并使用它调用glDrawArrays(...)一次。 However, when I do so it only draws the first sprite, and the other 200 are blank. 但是,当我这样做时它只绘制第一个精灵,而另外200个是空白的。

blueSpriteVertices[blueBatchNum * 4] = Vertex3DMake(xloc, yloc, zloc);
blueSpriteVertices[blueBatchNum * 4 + 1] = Vertex3DMake(xloc + size, yloc, zloc);
blueSpriteVertices[blueBatchNum * 4 + 2] = Vertex3DMake(xloc, yloc + size, zloc);
blueSpriteVertices[blueBatchNum * 4 + 3] = Vertex3DMake(xloc + size, yloc + size, zloc);
blueBatchNum++;
//^^This block of code^^ is called iteratively, adding data for various sprites
//(around 200) to the vertex array. "xloc", "yloc", etc. are private members of 
//this sprite class


//Draw the whole batch
glEnableClientState(GL_VERTEX_ARRAY);
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glColor4f(1, 1, 1, 1);

//This code is actually in the Texture2D class implementation, hence "_name"
//and "coordinates"
glBindTexture(GL_TEXTURE_2D, _name);
glVertexPointer(3, GL_FLOAT, 0, blueSpriteVertices);
glTexCoordPointer(2, GL_FLOAT, 0, coordinates);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_VERTEX_ARRAY);

I finally solved this problem by using GL_TRIANGLES instead of GL_TRIANGLE_STRIP, and handled the triangle strips manually. 我终于通过使用GL_TRIANGLES而不是GL_TRIANGLE_STRIP解决了这个问题,并手动处理了三角形条。 By doing so I was able to eliminate all the "strips" that it was interpreting in between my sprites. 通过这样做,我能够消除它我的精灵之间解释的所有“条带”。 Works like a charm now, and the batching definitely improved my game's performance astronomically. 现在就像魅力一样,配料肯定会提升我的游戏性能。

使用(GL_TRIANGLES而不是GL_TRIANGLE_STRIP适用于我(在Android上)

glDrawElements(GL_TRIANGLES, 6 * mSpriteCounter, GL_UNSIGNED_SHORT, (char*) NULL);

The glDrawArrays() last parameter should contain the number of vertices (in your case you have only 4). glDrawArrays()最后一个参数应该包含顶点数(在你的情况下你只有4个)。 Also you must have the same number of texture coordinates to match the drawn vertices! 此外,您必须具有相同数量的纹理坐标才能匹配绘制的顶点!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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