Pages

Thursday, September 8, 2011

What the flip yo... ID3DXSprite flipping

For a 2D platformer, it's often true that the "Run" animation frames are the same in either direction (run left, run right). It makes sense then to save texture space by allowing a sprite to be flipped.

While some sprite libraries come with the option to flip horizontally or vertically, the ID3DXSprite interface does not. If you're rolling your own sprite class using a quad, you can easily add this functionality by inverting the texture co-ordinates.

Another method of flipping, which works for ID3DXSprites as well, is to inverse the scale on the flipped axis.

Here's a simple pseudo code example:
D3DXVECTOR2 scale;
D3DXVECTOR2 position;
...
if(FlippedOnX)
{
   scale.x = -scale.x; //Invert the sprite on the x axis
   position.x += spriteWidth; //Shift the sprite by the amount of 'width' to re-position after the mirror flip
}

if(FlippedOnY)
{
   scale.y = -scale.y;
   position.y += spriteHeight;
}

Of course, you can get rid of the two if statements:
D3DXVECTOR2 scale;
D3DXVECTOR2 position;
...
scale.x = (scale.x * !FlippedOnX) + (-scale.x * FlippedOnX);
scale.y = (scale.y * !FlippedOnY) + (-scale.y * FlippedOnY);
position.x = posixion.x + (spriteWidth * FlippedOnX);
position.y = posixion.y + (spriteHeight * FlippedOnY);

This is far from secret knowledge, but when I was looking for an answer to this question, I found mostly short forum responses, such as: "Just invert the scale".  While this is to the point and it's easy enough to try for yourself, I figured an example and a brief explanation could have been of some use.

No comments:

Post a Comment