Texture from texturepacker in LibGDX
试图在(很棒的)LibGDX框架中绕过纹理package器,我需要帮助。
我想绑定一个纹理(根据网格,颜色
创建TextureRegion
首先,通过指向描述地图集的文本文件来创建
1 | TextureAtlas myTextures = new TextureAtlas("images/packed.txt"); |
然后,您可以在该地图集中查找
1 | TextureRegion region = myTextures.findRegion(fname); |
配置纹理网格
要在网格上绘制此纹理区域,您需要在支持纹理坐标的情况下初始化
1 2 | Mesh myMesh = new Mesh(..., new VertexAttribute(Usage.TextureCoordinates, 2,"y")); |
现在,在定义网格的浮点数组(传递给
1 2 3 4 5 6 7 8 9 10 | final int floatsPerVertex = 5; // 3 spatial + 2 texture float[] meshData = new float[numVerticies * floatsPerVertex]; for (int i = 0; i < numVerticies; i++) { meshData[(i * floatsPerVertex) + 0] = ... ; // x coordinate of i'th vertex meshData[(i * floatsPerVertex) + 1] = ... ; // y coordinate of i'th vertex meshData[(i * floatsPerVertex) + 2] = ... ; // z coordinate of i'th vertex meshData[(i * floatsPerVertex) + 3] = ... ; // u texture coordinate of i'th vertex meshData[(i * floatsPerVertex) + 4] = ... ; // v texture coordinate of i'th vertex } myMesh.setVertices(meshData); |
您可以使用
由于纹理很大(例如512x512),并且特定区域是该纹理的一小部分(例如20x20在128x128上),因此实际上您将最终给出仅利用整个512x512的20x20子集的网格纹理坐标图片。
渲染纹理网格
最后,在渲染时,需要绑定图像,并在渲染之前启用纹理:
1 2 3 4 | region.getTexture().bind(); Gdx.graphics.getGL10().glEnable(GL10.GL_TEXTURE_2D); myMesh.render(); Gdx.graphics.getGL10().glDisable(GL10.GL_TEXTURE_2D); |
请注意,这比应有的效率低得多。纹理图集的部分好处在于,它应该包含很多可以一起渲染的区域,因此您只需要绑定一个纹理,然后从那个绑定的纹理渲染很多不同的纹理网格。
使用以上说明使它起作用。
我不敢相信会有这么多人跑来问这个问题,因为这似乎是其他人想做的事情。
从接受的解决方案中,我创建了一个函数,该函数还可以对新的UV位置进行数学运算。
经过测试,它对我有用,但是由于我不是Java开发人员,因此请查看。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public Mesh RebuildMeshUVtoTextureRegion(Mesh ObjectMesh, TextureRegion UVMapPos) { int numFloats = ObjectMesh.getNumVertices() * ObjectMesh.getVertexSize() / 4; float[] vertices = new float[numFloats]; ObjectMesh.getVertices(vertices); int numIndices = ObjectMesh.getNumIndices(); short SourceIndices[] = new short[numIndices]; ObjectMesh.getIndices(SourceIndices); final int floatsPerVertex = 5; int TimesToLoop = ((vertices.length) /floatsPerVertex); float previousU; float previousV; float FullMapHeight = UVMapPos.getTexture().getHeight(); float FullMapWidth = UVMapPos.getTexture().getWidth(); float NewMapWidth = UVMapPos.getRegionWidth(); float NewMapHeight = UVMapPos.getRegionHeight(); float FullMapUPercent; float FullMapVPercent; for (int i = 0; i < TimesToLoop; i++) { previousU = (vertices[(i * floatsPerVertex) + 3]); previousV = (vertices[(i * floatsPerVertex) + 4]); FullMapUPercent = previousU / FullMapWidth; FullMapVPercent = previousV / FullMapHeight; vertices[(i * floatsPerVertex) + 3] = (NewMapWidth * FullMapUPercent) + UVMapPos.getU(); //New U vertices[(i * floatsPerVertex) + 4] = (NewMapHeight * FullMapVPercent) + UVMapPos.getV();//New V } ObjectMesh.setVertices(vertices); ObjectMesh.setIndices(SourceIndices); return ObjectMesh; } |