使用Monogame / XNA将精灵绘制到永久的Texture2d

时间:2013-11-22 20:19:36

标签: c# xna monogame texture2d

(来自Gamedevs的交叉帖子)

我正在与Monogame合作做一个2d精灵引擎。我已经很好地工作了,我可以在屏幕上移动大量的精灵,以及我想要的效果和位置。

昨晚我试图添加一项功能,但我无法让它正常工作。 我正在尝试创建移动的精灵可以留下的永久路径。所以我有一个大多数透明的PNG,上面有一些白线叫做“条纹”。我的想法是,我设置了一个新的Texture2D表面(称为streakoverlay),并将条纹绘制到它上面。

我切换回后台缓冲区并绘制:背景,streakoverlay,最后是精灵。条纹应该随着时间的推移而积累。它几乎可以工作,但我遇到的麻烦是streakOverlay似乎每次都清楚自己。我喜欢它的行为与没有这一行GraphicsDevice.Clear(Color.White);的图形显示行为相同 - 一切都会堆积在其中。

相反,它会重置为Purple透明颜色,该颜色是该纹理的默认颜色。有什么建议?这是渲染引擎的核心部分:

GraphicsDeviceManager graphics;
RenderTarget2D streakOverlay;
SpriteBatch spriteBatch;

private Texture2D bkg;
private Texture2D prototype;
private Texture2D streak;

//Initialize 
graphics = new GraphicsDeviceManager(this);
GraphicsDevice.Clear(Color.Transparent);
streakOverlay = new RenderTarget2D(GraphicsDevice, 200,200);

//Load Content
bkg = Content.Load<Texture2D>("bkg"); //Background image
prototype = Content.Load<Texture2D>("prototype"); //Prototype sprite that moves around
streak = Content.Load<Texture2D>("blueStreak"); //Trails being left by Prototype sprite

graphics.GraphicsDevice.SetRenderTarget(streakOverlay); 
GraphicsDevice.Clear(Color.Transparent); //Attempt to make the streakoverlay is fully transparent.
graphics.GraphicsDevice.SetRenderTarget(null);

//Draw
Random r = new Random();
graphics.GraphicsDevice.SetRenderTarget(streakOverlay); //Switch to drawing to the streakoverlay

spriteBatch.Begin();
//Draw some streaks that should accumulate
spriteBatch.Draw(streak, new Vector2(r.Next(0, 200), r.Next(0, 200)), null, Color.White, 0f, new Vector2(25, 25), 1f, SpriteEffects.None, 1f);
spriteBatch.End();

//Switch back to drawing on the back buffer.
graphics.GraphicsDevice.SetRenderTarget(null);

spriteBatch.Begin();
spriteBatch.Draw(bkg, new Rectangle(0, 0, 2000, 2000), Color.White);    //Draw our background
spriteBatch.Draw(streakOverlay, new Vector2(0, 0), Color.White); //Put the overlay on top of it
spriteBatch.Draw(prototype, new Vector2(_spritePrototype.getX, _spritePrototype.getY), null, Color.White, DegreeToRadian(rotationSprite), new Vector2(25, 25), .5f, SpriteEffects.None, 0f); //Draw the sprite that's moving around.
spriteBatch.End();

base.Draw(gameTime);

1 个答案:

答案 0 :(得分:2)

您需要使用RenderTarget2D的扩展构造函数,该构造函数需要4个参数并指定PreserveContents。假设渲染目标经常被重用,因此当它被设置时,它会被自动清除,除非设置了这个标志。