In this Udacity course, we have to read a JSON file generated by TexturePacker to compute the center of a sprite from a spritesheet. We have to consider whether the sprite is trimmed or not.
An spritesheet with untrimmed sprites looks like this (empty pixels in green):
While an spritesheet with trimmed sprites looks like this (empty pixels in green):
The difference, as you can probably tell, is that empty pixels are removed from the final spritesheet file.
So, if I add a circle.png
file of 32x32 pixels to my TexturePacker spritesheet, and the image's dimensions were only 24x24, TexturePacker would trim the image down to 24x24 and generate a png file of this size (assuming there was only one sprite) and the following JSON file:
{"frames": [
{
"filename": "circle.png",
"frame": {"x":0,"y":0,"w":24,"h":24},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":5,"y":5,"w":24,"h":24},
"sourceSize": {"w":34,"h":34},
"pivot": {"x":0.5,"y":0.5}
}],
...
}
It details the following information:
- frame: the coordinates, width and height of the sprite inside the spritesheet.
- trimmed: whether the empty pixels were removed or not.
- spriteSourceSize: the coordinates and size of the trimmed sprite inside the original image.
- sourceSize: the size of the original image.
I thought that, in order to get the center of the image, it was enough to calculate sprite.frame.w/2
and sprite.frame.h/2
, but, according to the course, this javascript is supposed to calculate the center:
//sprite is a javascript object that represents a sprite inside the 'frames' array
if (sprite.trimmed) {
cx = sprite.spriteSourceSize.x - (sprite.sourceSize.w * 0.5);
cy = sprite.spriteSourceSize.y - (sprite.sourceSize.h * 0.5);
}
Maybe it's something really simple, but I haven't been able to understand why they are using spriteSourceSize
, since we will be reading the spritesheet and not the original image.