简体   繁体   中英

Going back to SpriteBatch.Draw() after using GraphicsDevice.DrawUserPrimitives()

In my 2D XNA game, I've been trying to draw triangles. I've been following the tutorial here .

// Game1.FX is a static instance of Effect
Game1.FX.CurrentTechnique = Game1.FX.Techniques["Pretransformed"];

foreach (EffectPass pass in Game1.FX.CurrentTechnique.Passes)
{
    pass.Apply();

    Game1.GameInstance.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration);
}

// Exception is thrown when we go back to spriteBatch.Draw()
spriteBatch.Draw(Textures.Get("Projectiles\\laser01"), new Rectangle((int)compartment.Position.X, (int)compartment.Position.Y,
    compartment.CompartmentWeapon.MaxRange, 2), null, laserColour, gunRotation - compartment.CompartmentWeapon.ArcLOS, Vector2.Zero, SpriteEffects.None, 1);

I receive a System.InvalidOperationException when going back to the spriteBatch.Draw() from the GraphicsDevice.DrawUserPrimitives().

"A valid vertex buffer (and a valid index buffer if you are using indexed primitives) must be set on the device before any draw operations may be performed."

I would be grateful if anyone could point out why this is happening.

You must call spriteBatch.End() before your DrawUserPrimitives() . Then before you try to issue another spriteBatch.Draw() , you must issue another spriteBatch.Begin() .

SpriteBatch.Begin() sets up all of the buffers and staging for you in order to provide easy rendering functionality. As soon as you touch GraphicsDevice you risk making changes to things that the SpriteBatch may not be aware of, and restarting the SpriteBatch helps reset the pipeline to a known state.

Doing things on GraphicsDevice like changing the current RenderTarget or clearing a target are fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM