I’m developing a 2D videogame in Android, using JAVA and OpenGL-ES.
I’m having an issue with I think it’s the Garbage Collector. Every few seconds, the game freezes, no matter what I’m doing.
I have been reading some documentation and so on about it, and I removed all the loop iterators I had, now I use for(i=0,…), among others solutions. The case is, it didn’t do anything with the perfomance…
I have been looking my code and I found something I think that could be making problems, and it’s the way I change between sprites in an animation.
For instance, I have a hero which can move pressing some keys. When it walks, his sprite changes between frames. To do this, I move the texture buffer to aim the part of the image I want. And every time it does, I use this function:
protected void SetTextureBuffer(float xo, float xf, float yo, float yf) {
float textureVertexs[] = {
xo, yf, // top left
xf, yf, // bottom left
xf, yo, // top right
xo, yo // bottom right
};
// a float has 4 bytes so we allocate for each coordinate 4 bytes
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(textureVertexs.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
// allocates the memory from the byte buffer
textureBuffer = byteBuffer.asFloatBuffer();
// fill the vertexBuffer with the vertices
textureBuffer.put(textureVertexs);
// set the cursor position to the beginning of the buffer
textureBuffer.position(0);
}
It allocates memory to create the buffer every time is called, which could be a lot of times every second, since there are more entities with animations…
Do you think this could be a problem? Or Am I looking this wrongly? If this is a problem… how could I solve this in another more efficient way?
Try removing these lines:
Allocate
textureBufferonce in your class constructor/initializer. No need to recreate the buffer again since you don’t need to keep previous data. So you just overwrite the old data in the same buffer.