Search code examples
c#graphicsspritemonogame

Failing to flip sprite with simplified Draw method


I'm making a game in which I draw sprites from a sprite sheet. My Sprite class has an integer property called spriteDirection, and when this is equal to +1 the sprite faces right, and when it is equal to -1 the sprite is flipped to face the left. I have been using this Draw method successfully:

public void Draw(SpriteBatch spriteBatch)
        {
            if (draw)
            {
                int drawX = (int)(spritePosition.X - spriteOffset.X);
                int drawY = (int)(spritePosition.Y - spriteOffset.Y);

                if (texture != null)
                {
                    spriteBatch.Draw(texture, new Rectangle(drawX, drawY, frameWidth, frameHeight), rSpriteSourceRectangle, Color.White);
                }
            }
        }

The rSpriteSourceRectangle is calculated like this:

private Rectangle rSpriteSourceRectangle
        {
            get
            {
                if (spriteDirection == -1)
                {
                    return new Rectangle(frameOffsetX + (frameWidth * (currentFrame + 1)), frameOffsetY, -frameWidth, frameHeight);
                }
                else
                {
                    return new Rectangle(frameOffsetX + (frameWidth * currentFrame), frameOffsetY, frameWidth, frameHeight);
                }
            }
        }

This all works absolutely fine. However I want to be able to switch to using this new Draw method:

public void Draw(SpriteBatch spriteBatch)
        {
            if (draw)
            {
                Vector2 positionDraw = spritePosition - spriteOffset;
                if (texture != null)
                {
                    spriteBatch.Draw(texture, positionDraw, rSpriteSourceRectangle, Color.White);
                }
            }
        }

This works, provided my spriteDirection property is equal to 1 (so the sprite faces right). If I make it equal to -1, the sprite disappears from the screen. I can't work out why this is happening. I'm sure it's something simple, so hopefully some nice person can point me in the right direction!

Thanks!


Solution

  • I have found a way around the problem by using a different Draw overload:

    Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth);