Weird effect using SpriteBatch.Draw()

Hi there,

Is it possible to draw in a RenderTarget inside the Game.Update() method?

I’m trying to dark a rectangular area inside a RenderTarget but I’m getting a weird effect and I don’t know why this is happening.

Here’s a screenshot which show the RenderTarget before trying to dark the area and after

Here’s the code to dark the area

Game1.spriteBatch.Begin();

  Game1.spriteBatch.Draw(
    Game1.inventoryTexture,
    color: Color.DarkGray,
    sourceRectangle: new Rectangle(45, 0, 45, 45),
    destinationRectangle: new Rectangle(45, 0, 45, 45));

Game1.spriteBatch.End();

The expected behavior is to dark only the shield area but it does that plus set black the rest of the RenderTarget.

But if I use the same Draw() statement in the constructor of the class it works as expected. Here’s the code

graphicsDevice.SetRenderTarget(inventoryRenderTarget);
graphicsDevice.Clear(Color.CornflowerBlue);

Game1.spriteBatch.Begin();

Game1.spriteBatch.Draw(Game1.inventoryTexture, Vector2.Zero, Color.White);

Game1.spriteBatch.Draw(
  Game1.inventoryTexture,
  color: Color.DarkGray,
  sourceRectangle: new Rectangle(45, 0, 45, 45),
  destinationRectangle: new Rectangle(45, 0, 45, 45));

Game1.spriteBatch.End();

In this constructor I draw the whole inventory and then dark the shield Icon. And the effect is the expected as you can see in the screenshot

Any help will be appreciated.

I recently had a similar issue in (this) thread. I know its not the same, but it might be worth trying the solution…
I could draw my stuff once, (like in the constructor) but when I updated, everything went black…

Check out the solution, see if its good for you too :slight_smile:

Can you show all your drawing code for this failing case?

I think its down to that overload when creating the rendertarget:

‘RenderTargetUsage.PreserveContents’

otherwise, it blacks the whole thing out between frames… -Why his code only works for the first frame / constructor…

I think it’s about the parameter RenderTargetUsage.PreserveContents as @monopalle mentioned.

I’ll do some tests and if it doesn’t work I’ll send you a new project with the issue because the code actually has a lot of dependencies and will be hard to understand.

Thank you guys.

I think I’m in the same situation. I’m pretty sure the parameter RenderTargetUsage.PreserveContents will fix the issue.

I’ll let you know.

Thank you.

Umm is it a single texture? would an alpha setting not suffice?

Valentine.