# Can you offset the horizontal flip in SpriteEffects XNA?

As the title suggests I need to know if there is a way to offset the SpriteEffects.FlipHorizontally component in the XNA draw method. My reason for this is the sprite I am attempting to flip is not centered, the result is that the sprite does not rotate as expected and causes unexpected collisions when flipping. I have the alternative of redoing all the textures in the sprite sheet to centre them up however I'm wondering if there is also a quick solution that can be added into the code?

My tests so far have shown that the origin of the texture seems to have no effect on where it is flipped otherwise I would just offset my origin and gone with that.

You will need to mirror the origin of your sprite.

Simply subtract the original origin from the width of the sprite.

Something like:

Vector2 origin = new Vector2(20, 10);
int spriteWidth = 100; // from sourceRectangle or texture width
SpriteEffects spriteEffects = SpriteEffects.None;

if (flipSpriteHorizontallyAroundOrigin)
{
origin.X = (float)spriteWidth - origin.X;
spriteEffects |= SpriteEffects.FlipHorizontally;
}


Flipping a sprite around a given offset from its center is equivalent to first flipping the sprite normally (around its center), then offsetting the result.

I haven't used XNA in a while, but you can do this by adding a translation to your drawing matrix.

A somewhat hackier way to do this is to call SpriteBatch.draw with an origin and pass a scale parameter with the relevant component set to -1. Since the scaling transform honours the origin and scaling by negative one flips, this should flip the sprite about that origin.

• If you use a negative scale, you also need to render backfaces (use RasterizerState.CullNone), otherwise you'll see nothing. – Andrew Russell Sep 17 '14 at 2:40
• Also it's best to use the parameters to Draw, rather than setting a matrix on Begin, for this particular case. – Andrew Russell Sep 17 '14 at 2:43

I recommend you use an offset with your mirroring. this way, you can control where the symetry happens. Back when I was using XNA, I used to always consider the position of an object in the center and that certainly helped with all the flipping I needed.

I used to take the 6th overload to the spriteBatch.Draw(...) method if you're interested.