【问题标题】:Sprite drawn twice monogame雪碧画了两次monogame
【发布时间】:2013-09-11 07:16:52
【问题描述】:

我正在 Windows Phone 8 上学习 Monogame。在我的 Sprite 类中,它是精灵对象的基类,我有以下方法

    public void Draw(SpriteBatch batch)
    {
        batch.Draw(texture, Position, color);
        DrawSprite(batch);
    }

    protected virtual void DrawSprite(SpriteBatch batch)
    {
    }

我有一个源自 Sprite 类的 Car 类。在里面我有

    protected override void DrawSprite(SpriteBatch batch)
    {

        batch.Draw(texture, Position, null, Color.White, MathHelper.ToRadians(rotateAngle),
            new Vector2(texture.Width / 2, texture.Height / 2), 1.0f,
            SpriteEffects.None, 0.0f);    
    }

然后在我的MainGame 类中,我使用以下方法绘制屏幕

    protected override void DrawScreen(SpriteBatch batch, DisplayOrientation displayOrientation)
    {
        road.Draw(batch);
        car.Draw(batch);
        hazards.Draw(batch);
        scoreText.Draw(batch);
    }

问题是汽车精灵被绘制了两次。如果我删除

batch.Draw(texture, Position, color);

Sprite 类的Draw 方法中,没有像按钮背景那样绘制其他一些精灵。

我想我的问题是如何仅在存在但不存在时调用覆盖方法

batch.Draw(texture, Position, color);

    public void Draw(SpriteBatch batch)
    {
        batch.Draw(texture, Position, color);
        DrawSprite(batch);
    }

【问题讨论】:

    标签: c# windows-phone-8 xna sprite monogame


    【解决方案1】:

    你几乎明白了,问题是Car 类应该覆盖Draw 方法,而不是DrawSprite 方法。

    所以去掉 DrawSprite 方法,将 Draw 方法标记为虚拟,如下所示:

    public virtual void Draw(SpriteBatch batch)
    {
        batch.Draw(texture, Position, color);
    }
    

    然后像这样覆盖Car 类中的Draw 方法:

    public override void Draw(SpriteBatch batch)
    {
        batch.Draw(texture, Position, null, Color.White, MathHelper.ToRadians(rotateAngle),
            new Vector2(texture.Width / 2, texture.Height / 2), 1.0f,
            SpriteEffects.None, 0.0f);    
    }
    

    之所以如此,是因为 C# 中的类型系统推断在运行时调用哪个方法的方式。例如,将类型声明为Sprite 将调用默认的Draw 方法,但将其声明为Car 将调用重写的Draw 方法。

    var sprite = new Sprite();
    sprite.Draw(batch);
    
    var car = new Car();
    car.Draw(batch);
    

    祝你好运! :)

    【讨论】:

      【解决方案2】:

      当您调用car.Draw(batch) 时,您正在绘图:

      batch.Draw(texture, Position, color);
      

      batch.Draw(texture, Position, null, Color.White, MathHelper.ToRadians(rotateAngle),
          new Vector2(texture.Width / 2, texture.Height / 2), 1.0f,
          SpriteEffects.None, 0.0f); 
      

      在您的Car 类中,您不必覆盖DrawSprite,而是Draw 本身。这样,您将只绘制您需要的精灵。我想这对所有其他类来说可能是个好主意。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多