"Begin cannot be called again..." error when using BeforeDraw event

May 16, 2013 at 4:32 AM
Hi there,

Im trying to draw my player on the first layer of my map using BeforeDraw like so:

In Initialize():
map.Layers[1].BeforeDraw += new xTile.Layers.LayerEventHandler(e_OnBeforeLayerDraw);
My handler & draw class look like this:
        private void e_OnBeforeLayerDraw(object sender, xTile.Layers.LayerEventArgs  layerEventArgs)
            SpriteBatch spriteBatch = xdd.SpriteBatchAlpha;
            player.Draw(pGameTime, spriteBatch);

         public override void Draw(GameTime gameTime)
            //map.Draw(mapDisplayDevice, GameRef.viewport);
            map.Draw(xdd, GameRef.viewport);
            //world.DrawLevel(gameTime, GameRef.SpriteBatch, player.Camera);
            //player.Draw(gameTime, GameRef.SpriteBatch);
This is my player.Draw()
        public void Draw(GameTime gameTime, SpriteBatch spriteBatch)

            character.Draw(gameTime, spriteBatch);

The error appears in player.Draw() on my spriteBatch.Begin (first line). I get a "Begin cannot be called again until End has been successfully called".

I guess this is because xTile has started a begin somewhere and when the event handler fires off the .end() has not been reached. However, I need a begin() so I can put my Camera.Transformation Matrix in, or else my camera does not function properly.

Is there any way for me to fix this?

Any help is greatly appreciated.
May 16, 2013 at 9:59 AM
I don't know what to suggest until I at least figure out why you need the camera transform. Are you using this to pan around the level or doing more sophisticated effects?
May 17, 2013 at 5:07 AM
I had another look as to why it was needed and it turns out it was for assistance with a Zoom functionality with our old tile system. It also prevented having to minus off the camera position when drawing the player sprite.

Like so:
                texture, position - camera.Position,
It all works now without the transform. However there is a bit of stuttering when walking. I'm just investigating whether this has to do with the drawing between layers.

Thanks for your help!
May 17, 2013 at 11:33 AM
I'm glad you sorted the problem. As to the stuttering, perhaps the player position calculation is not in synch with the Viewport coordinates? Let me know how that goes and I'll try to help out if I can.