Sunday, June 12, 2016

xna 4.0 - Using 2D sprites and 3D models together



I have gone through a few posts that talks about changing the GraphicsDevice.BlendState and GraphicsDevice.DepthStencilState (SpriteBatch & Render states). . however even after changing the states .. i cant see my 3D model on the screen.. I see the model for a second before i draw my video in the background. . If i dont play my video then i can see the 3D model ..Here is the code:


GraphicsDevice.Clear(Color.AliceBlue);
spriteBatch.Begin();

if (player.State != MediaState.Stopped)
{
videoTexture = player.GetTexture();
}

Rectangle screen = new Rectangle(GraphicsDevice.Viewport.X, GraphicsDevice.Viewport.Y, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);


// Draw the video, if we have a texture to draw.
if (videoTexture != null)
{
spriteBatch.Draw(videoTexture, screen, Color.White);

if (Selected_underwater == true)
{
spriteBatch.DrawString(font, "MaxX , MaxY" + maxWidth + "," + maxHeight, new Vector2(400, 10), Color.Red);
spriteBatch.Draw(kinectRGBVideo, new Rectangle(0, 0, 100, 100), Color.White);

spriteBatch.Draw(butterfly, handPosition, Color.White);

foreach (AnimatedSprite a in aSprites)
{
a.Draw(spriteBatch);
}
}

if(Selected_planet == true)
{

spriteBatch.Draw(kinectRGBVideo, new Rectangle(0, 0, 100, 100), Color.White);
spriteBatch.Draw(butterfly, handPosition, Color.White);
spriteBatch.Draw(videoTexture,screen,Color.White);

GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

foreach (_3DModel m in Solar)
{

m.DrawModel();
}
}
spriteBatch.End();

Answer



The problem you are having is because SpriteBatch, by default[1], buffers all rendering until End is called.


It's not really a problem with render states. The states you specify in Begin (or the default states if you specify nothing) are only set during End.


What is happening is that, by calling End after drawing your model, you are rendering all your sprites over the top of your model.


Just split your rendering into multiple batches, or call End earlier (whichever suits) and it should work correctly. Be sure that Begin/End pairs always match up!





[1] : Except in SpriteSortMode.Immediate, which does everything, well, immediately. It sets states in Begin and draws a sprite for each Draw. Because of this it can't do batching and so is generally slower.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...