Search code examples
javalibgdxdrawingtexturestexture-packing

libGDX - TextureRegion drawing weird when scaled


Having a weird issue.

I have a Texture with four frames of a sprite Animation. Each frame is loaded as a TextureRegion.

Most of the time the Animation play without any issues, but occasionally it will draw too much of the Texture in one frame.

Here's an example of what I mean:

enter image description here

As you can see the UFO has a red bar on the left side of it. That red bar is part of a frame on the outside of the TextureRegion bounds stated in my code. (The red frame is just there to make it easier for me to measure, since there is transparency on all the corners)

Here's the Texture:

enter image description here

In the above sprite sheet the red frame for the slide at the top has the bounds 0, 0, 202, 71. The TextureRegion for the frame of the anim is 1, 1, 200, 69 -- at no point should any of the red frame be displayed, as far as I can tell.

I realise as a workaround I could just set the frame as transparent now that I have the measurements I need, but I'd like to keep the red frame in case I need to take the measurements again later, or replace the sprite images, etc, and really a workaround is just a band-aid whereas I'm hoping to find a proper solution to address the root of the issue -- the fact that it's drawing wrong seems to indicate a larger problem than what exists just in this particular case (eg, in a densely-packed Texture it might draw pixels from a different sprite frame or even a different sprite or a menu image or something like that).

Oh and one last note, in case it's helpful: when the SpriteBatch displays the image it applies a rotation based on the movement of the UFO (tilts to the left when moving left, etc). The glitchy red bars sometimes show up on the top, right, bottom, or left randomly (though most of the time they don't show up at all) however they only seem to show up when the UFO has a rotation of zero. (Again, I realise I could just include a check to see if rotation is 0 and then call the SpriteBatch.draw() method without the rotation figure, but that too would be treating the symptom rather than addressing the root of the problem).

Any thoughts from the learned masters?


Solution

  • Your frames of animation need padding around them to account for rounding error. Put two pixels of clear pixels all around each image. If you use TexturePacker to combine the images into your file, it will automatically add the two pixels of padding by default.

    If you name your four images with an underscore-frame number suffix, like myAnimation_0.png, myAnimation_1.png, myAnimation_2.png, and myAnimation_3.png, then when you load your TextureAtlas, it allows you get the animation very easily.

    Array<TextureRegion> myAnimationFrames = textureAtlas.findRegions("myAnimation");