Java – libGDX rendering TextureRegion rendering too much

libGDX rendering TextureRegion rendering too much… here is a solution to the problem.

libGDX rendering TextureRegion rendering too much

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

Minecraft contains many different 64×64 pixel blocks that are drawn by SpriteBatch using a camera to fit the screen. My 640x640px resource file contains all these images. Block textures are located in my resource files at (0, 0), (0, 64), (64, 0)、… Wait a minute.
When my application starts, I load textures 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 blocks) are drawn as if the rectangle of the TextureRegion is positioned incorrectly – it draws the bottommost pixel row of the texture above the block (in the resource texture) as its topmost pixel row. Most blocks render correctly, and I checked multiple times that I entered the correct position.

Strangely, when I launch the game on my computer instead of my android device, the texture is drawn correctly!

A lot of people cite filters when searching for solutions, but linear and recent don’t work for me. 🙁

Hopefully I can explain the problem in an understandable way and you have any ideas on how to solve this problem (= how to draw only the textured areas I want to paint)!

Best regards

EDIT: This error only appears in certain places. When I draw two blocks with the same texture in different positions, one of them draws correctly and the other incorrectly: I don’t understand ….

Solution

When packaging into a texture, you should always leave white space between images, because if you use an FILTER_LINEAR for each pixel (which I think is the default), it will sample from the four closest pixels. If your image does not have an empty pixel fill, it will fetch pixels from neighboring images for all edge pixels.

Three options to solve your problem:

  1. Manually add space between images in the texture file
  2. Stop using FILTER_LINEAR (but if you don’t draw in the original image dimensions, such as scaling the image, you will get unsightly results).
  3. With Libgdx Texture Packer, it has a build feature that does that when you package images

Related Problems and Solutions