首页 > 解决方案 > 无法使用简化的 Draw 方法翻转精灵

问题描述

我正在制作一个从精灵表中绘制精灵的游戏。我的 Sprite 类有一个名为 spriteDirection 的整数属性,当它等于 +1 时,精灵面朝右,当它等于 -1 时,精灵翻转面朝左。我一直在成功使用这个 Draw 方法:

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);
                }
            }
        }

rSpriteSourceRectangle 的计算方式如下:

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);
                }
            }
        }

这一切都很好。但是我希望能够切换到使用这个新的 Draw 方法:

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

这可行,前提是我的 spriteDirection 属性等于 1(所以精灵面朝右)。如果我让它等于-1,精灵就会从屏幕上消失。我无法弄清楚为什么会这样。我敢肯定这很简单,所以希望有好人能指出我正确的方向!

谢谢!

标签: c#graphicsspritemonogame

解决方案


我通过使用不同的 Draw 重载找到了解决该问题的方法:

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

推荐阅读