-2
\$\begingroup\$

When using this code:

public static Texture2D ShowHealthBar(SpriteBatch spriteBatch,Texture2D empty, Texture2D full, float health)
    {

        spriteBatch.Begin();
        RenderTarget2D healthBarTarget = new RenderTarget2D(Game1.graphics.GraphicsDevice, full.Width, full.Height);


        Game1.graphics.GraphicsDevice.SetRenderTarget(healthBarTarget);
        spriteBatch.Draw(empty, new Vector2(0, 0), Color.White);
        Game1.graphics.GraphicsDevice.SetRenderTarget(null);

        spriteBatch.End();
        return (Texture2D)healthBarTarget;
    }

the texture is purple.

When inserting Game1.graphics.GraphicsDevice.Clear the texture has the clear color.

Why doesn't the sprite batch work?

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Try moving your calls to GraphicsDevice.SetRenderTarget outside of your calls to SpriteBatch.Begin and SpriteBatch.End. \$\endgroup\$ Commented Apr 22, 2013 at 16:43
  • \$\begingroup\$ No problem, let me write this up in an answer. \$\endgroup\$ Commented Apr 22, 2013 at 17:17

1 Answer 1

1
\$\begingroup\$

The default behavior of SpriteBatch is to save its actual call to the GPU until you call .End(), rather than immediately (available by optional argument) when you call .Draw(). This allows it to reduce the total number of draw calls it makes, which is an important optimization. But switching the render target back before calling End() means that the draw goes to the wrong place, not the RenderTarget that was set when you called Draw().

So, call End() before switching the target back to the default.

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.