我正在開發自己的XNA基於tile的遊戲,並且我遇到了RenderTarget2D問題。 我嘗試在屏幕上繪製背景圖像,並在屏幕上繪製我的播放器,並且它工作正常!但是當我嘗試在運行時使用RenderTarget2D將塊紋理添加到遊戲中時,我的屏幕開始以紫色閃爍。 每當我用RenderTarget2D創建一個新塊時,都會發生這種情況。在運行時創建RenderTarget2D會使我的屏幕以紫色閃爍
下面是一些代碼:
protected override void Draw(GameTime gameTime)
{
this.DrawPlayer(gameTime);
this.DrawWorld(gameTime);
base.Draw(gameTime);
}
private void DrawPlayer(GameTime gameTime)
{
GraphicsDevice.SetRenderTarget(Main.PlayerRenderTarget);
GraphicsDevice.Clear(Color.Transparent);
this.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, this.Camera.Transform);
SpriteBatch.Draw(this.Background, new Vector2(this.Screen.X, this.Screen.Y), Color.White);
this.Player.Draw(SpriteBatch);
SpriteBatch.End();
GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.Transparent);
SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
SpriteBatch.Draw(Main.PlayerRenderTarget, Vector2.Zero, Color.White);
SpriteBatch.End();
}
private void DrawWorld(GameTime gameTime)
{
Main.World.Draw(SpriteBatch, this.Screen);
}
世界抽獎:
public void Draw(SpriteBatch SpriteBatch, System.Drawing.RectangleF Screen)
{
foreach (Chunk CurrentChunk in this.WorldChunks.Where(SomeChunk => SomeChunk.Bounds.IntersectsWith(Screen)))
{
CurrentChunk.Draw(SpriteBatch);
}
}
組塊抽獎:
public void Draw(SpriteBatch spriteBatch)
{
if (this.ChunkTexture == null)
{
this.CreateChunk(spriteBatch);
}
else
{
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
spriteBatch.Draw(this.ChunkTexture, this.ChunkPosition, Color.White);
spriteBatch.End();
}
}
public void CreateChunk(SpriteBatch spriteBatch)
{
RenderTarget2D CurrentRenderTarget = new RenderTarget2D(Chunk.GraphicsDevice, (int)this.Bounds.Width, (int)this.Bounds.Height);
Chunk.GraphicsDevice.SetRenderTarget(CurrentRenderTarget);
Chunk.GraphicsDevice.Clear(Color.Transparent);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
foreach(Block in Chunk)
{
spriteBatch.Draw(BlockTexture, BlockPosition, Color.White);
}
spriteBatch.End();
Chunk.GraphicsDevice.SetRenderTarget(null);
Chunk.GraphicsDevice.Clear(Color.Transparent);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
spriteBatch.Draw(CurrentRenderTarget, ChunkPositon, Color.White);
spriteBatch.End();
CurrentRenderTarget.GetData<Color>(Chunk.Colors);
this.Texture = new Texture2D(Chunk.GraphicsDevice, (int)this.Bounds.Width, (int)this.Bounds.Height);
this.Texture.SetData<Color>(Chunk.Colors);
this.IsLoaded = true;
CurrentRenderTarget.Dispose();
}
每當 「CreateChunk」 之稱,在屏幕上閃爍持續約0.1秒用紫色或黑色,然後在一切都很好。
當我使用Chunk.GraphicsDevice.Clear(Color.Transparent)時,屏幕閃爍黑色,但是當我刪除該行時,屏幕開始以紫色閃爍。
所以我想讓這個「閃爍」消失,因爲它非常令人不安。
請幫我弄清楚爲什麼會發生。
謝謝,弗拉德。
編輯:
「閃爍」似乎只適用於背景圖片和玩家圖片,但不適用於我繪製的圖塊。
謝謝!你是對的,我只需要刪除Dispose()方法!非常感謝你! – user3303408