While trying some new things after working all days, I encountered something annoying .. when I used texturepacker gui from codeandweb, the packer packs my image into one and use offset to maximize its compression.
This kind of packing is actually good, but it’s a little annoying because we must set the offset in libgdx to actually make the animation position line-up.
I browsed through google to find how to actually get the offset and apply it to the animation function in libgdx, but luck not in my side for a whole day … ah, as reminder I used this code to apply rotation from the left bug, because if you used the sprite as it is, you will get the same as the sprite above for animation.
1 2 3 4 5 6 7 8 |
if (textureRegion instanceof TextureAtlas.AtlasRegion && ((TextureAtlas.AtlasRegion) textureRegion).rotate) { batch.draw(textureRegion, 0, 0, 0, 0, textureRegion.getRegionHeight(), textureRegion.getRegionWidth(), 1, 1, 0, true); } else { batch.draw(textureRegion, 0, 0); } |
The code above will make your animation looks just like this ..
After a whole day searching with no actual result, I find some method to get the offset and apply it to the animation..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public void render () { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); elapsedTime += Gdx.graphics.getDeltaTime(); TextureRegion textureRegion = animation.getKeyFrame(elapsedTime, true); height = ((TextureAtlas.AtlasRegion) textureRegion).offsetX; width = ((TextureAtlas.AtlasRegion) textureRegion).offsetY; int posx = Math.round(height) + 2; int posy = Math.round(width) + 2; if (textureRegion instanceof TextureAtlas.AtlasRegion && ((TextureAtlas.AtlasRegion) textureRegion).rotate) { batch.draw(textureRegion, posx, posy, 0, 0, textureRegion.getRegionHeight(), textureRegion.getRegionWidth(), 1, 1, 0, true); } else { batch.draw(textureRegion, posx, posy); } batch.end(); } |
The code is really simple, when you see the offset in the .atlas / .pack file it was actually means that the size + (offset * 2) + 2 = original sprite size before packed.
for example this line
1 2 3 4 5 6 |
rotate: true xy: 2, 2 size: 190, 167 orig: 250, 250 offset: 29, 41 index: -1 |
means that, the image is rotated, the xy is the border, the size is the compressed packed size ( height + width ), the orig is the original size ( height + width ), and offset is the difference between size and orig …
1 2 |
x = 190 + (29 x 2) + 2 = 250 y = 167 + (41 x 2) + 2 = 250 |
It was calculate just like that, so to actually position so the animation were aligned perfectly you need to give additional code like below
I hope this helped newbie like me who use libgdx animation that use offset and texturepacker … if you have something to correct, feel free to use the comment box, cheers 🙂