0

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):

enter image description here

While an spritesheet with trimmed sprites looks like this (empty pixels in green):

enter image description here

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.

Federico
  • 3,650
  • 4
  • 32
  • 45

1 Answers1

2

In your case the circle is centered.

This delivers the same values as you would get when simply divide the frame size.

Your sprite (circle) might also be located in the top left corner of the original sprite. Transparent pixels all to the right and bottom.

spriteSourceSize: {"x":0, "y":0, "w":24, "h":24}

So the x and y coordinates are both 0, not 5. Your calculation would be off by 5 pixels in x and y direction.

I can't see the course (it requires logging in) but this is what this calculations takes into account.

Andreas Löw
  • 1,002
  • 8
  • 15