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



(来自Gamedevs的交叉帖子)

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

昨晚我试着添加了一个功能,但我没能让它正常工作。我正在尝试创建移动精灵可以留下的永久轨迹。所以我有一个基本透明的PNG,上面有一些白线,叫做"条纹"。我的想法是建立一个新的Texture2D表面(称为条纹覆盖),并在上面绘制条纹

我切换回后缓冲区并绘制:背景、条纹覆盖,最后是它上面的精灵。条纹应该会随着时间的推移而累积。它几乎起作用,但我遇到的问题是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);

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

最新更新