3
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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;
}
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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.

flip, then offset

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.

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

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.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.