4
votes

I want to develop a simple 2D side scrolling game using libGDX.

My world contains many different 64x64 pixel blocks that are drawn by a SpriteBatch using a camera to fit the screen. My 640x640px resource file contains all these images. The block textures are positioned at (0, 0), (0, 64), (64, 0), ... and so on in my resource file. When my app launches, I load the texture and create many different TextureRegions:

    texture = new Texture(Gdx.files.internal("texture.png"));
    block = new TextureRegion(texture, 0, 0, 64, 64);
    block.flip(false, true);
    // continue with the other blocks

Now, when I render my world, everything seems fine. But some blocks (about 10% of my blocks) are drawn as if the TextureRegion's rectangle was positioned wrong - it draws the bottommost pixel row of the above (in the resource texture) block's texture as its topmost pixel row. Most of the blocks are rendered correctly and I checked that I entered the correct position multiple times.

The odd thing is, that when I launch the game on my computer - instead of my android device - the textures are drawn correctly!

When searching for solutions, many people refer to the filter, but neither of both Linear and Nearest works for me. :(

Hopefully, I was able to explain the problem in an accessible way and you have any ideas how to fix that (= how to draw only the texture region that I want to draw)!

Best regards

EDIT: The bug does only appear at certain positions. When I draw two blocks with the same texture at different positions, one of them is drawn correctly and the other is not.. I don't get it....

1
I can't think of a solution but I suggest you to look at the LibGdx Texture Packer. Everything will be packed and unpacked automatically and I don't think that you will have this strange drawing problem. - Yasen Bagalev
Sounds like a texture filtering problem. Either that, or you're converting floating-point co-ordinates to integers somewhere in your program and accidentally truncating (rounding down), so 63.99999 is becoming 63. - Dan Hulme

1 Answers

4
votes

You should always leave empty space between your images when packing into one texture, because if you use FILTER_LINEAR (which I think is default) for every pixel it will sample from the four nearest pixels. And if your images are without empty pixels padding,for all edge pixels it will get pixels from the neighbor image.

So three options to solve your issue:

  1. Manually add space between images in you texture file
  2. Stop using FILTER_LINEAR (but you will get ugly results if you are not drawing in the native image dimentions e.g. scaling the image)
  3. Use the Libgdx Texture Packer, it has a build it functionality to do just that, when you pack your images