Sunday, December 23, 2012

Trimmed animating sprite offsets

With all the headway I have made with the exporter for the Texture Packer (http://www.codeandweb.com/). I am now setup that ALL my sprites come in from the texture atlas. This has caused some issues of course, related to animating sprites and trimming them.

I have the main hero sprites running in a 15 frame cycle. All his frames are rendered inside the middle of an area of the sprite, as you see below.

Then we have another part of the animation where Kal takes up a whole different area of the sprite, as you can see below.
When these are trimmed only the actual rectangular area containing colored pixels is placed into the new Texture Atlas image. Which means that the size of the sprites for rendering has of course changes.

However we also need to know where the new center offset is relative to the original frame. I need this as the artist has painstakingly placed each animation frame relative to its previous one. So in a flipbook style the animation looks like it should. However IF you render these trimmed sprites from center with no offset, you get a Very awkward looking run cycle. In fact what happens is poor Kal Bobs up and down and backwards and forwards, like he is stuck on a Yo-yo string.

To fix this I could have a table of X and Y offsets I can apply to the rendering position. However I hate that solution. I want the export to have all the information I require to render the sprites correctly. Now as it happens the Texture Packer can export the offsets for me. Yahoo I thought, only to find later there is an actual bug that means it is currently not outputting.

After a quick Tweet or two with Andreas (the coder of Texture Packer) he came to the same conclusion I did, that I should be able to calculate it from some other data that the exporter can export. So off I went to make it happen. In the end it was very easy.

 Here is where I calculate the top corner offset (my renderer uses the top left corner as its origin, so I compensate by using my xpos and simply minusing half the width...) 
int16 xOrigin = sprite_atlas[_sa_index]->offset[0];
int centerOffsetX = (int)(((float)(sprite_atlas[_sa_index]->originalSize[0]/2) - xOrigin) * _scale);

Using this I can render my sprite, scaled or not at the correct location. Looks good too and smooth.

Next up is to sort out the offset for the X flipped sprites.. bah! Always more to do.

G'night
Da Voodoochief

1 comment: