Hey, I’m having trouble with overlapping 3d objects. My 3D rendered models/objects are drawn on top based on which draw method gets called last instead of basing it off the pixel’s position relative to the camera.
I asked in the Discord and I was told that either my “depth read” or “depth write” are failing. My “Depth read” is I assume setting the DepthStencilState to default:
graphicsDevice.DepthStencilState = DepthStencilState.Default;
And the depth write is this right:
GraphicsDevice.Clear(Color.CornflowerBlue);
GraphicsDevice.Clear(ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
I’ve tried everything. My only theory left is that I keep resetting the graphicsDevice Vertexbuffer by this line of code
graphicsDevice.SetVertexBuffer(shape.vertexBuffer);
But ChatGPT informed me that isn’t a problem. Does anyone have an idea where my problem lies?
Here is how I draw my 3D objects
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch) {
graphicsDevice.DepthStencilState = DepthStencilState.Default;
graphicsDevice.BlendState = BlendState.Opaque; // Spritebatch sets it default to AlphaBlend
base.Draw(gameTime, spriteBatch);
Draw3DModels();
Draw3DShapes();
}
private void Draw3DModels() {
foreach (ThreeDGameObject threeDGameObject in ThreeDObjects) {
Model model = threeDGameObject.model;
foreach (ModelMesh mesh in model.Meshes) {
foreach (BasicEffect effect in mesh.Effects) {
// Transformations
Matrix worldMatrix = Matrix.CreateTranslation(threeDGameObject.Position) *
Matrix.CreateFromYawPitchRoll(threeDGameObject.Rotation.Y, threeDGameObject.Rotation.X, threeDGameObject.Rotation.Z);
effect.World = worldMatrix;
effect.View = camera.View;
effect.Projection = camera.Projection;
// Light
// effect.AmbientLightColor = new Vector3(1f, 0, 0);
// effect.EnableDefaultLighting();
// Other shader settings
effect.TextureEnabled = true;
effect.Alpha = threeDGameObject.Alpha;
effect.CurrentTechnique.Passes[0].Apply();
}
mesh.Draw();
}
}
}
private void Draw3DShapes() {
basicEffect.Projection = camera.Projection;
basicEffect.View = camera.View;
basicEffect.World = camera.World;
// Draw all shapes
foreach (Shape shape in shapes) {
// Transformations
Matrix worldMatrix = Matrix.CreateTranslation(shape.Position) *
Matrix.CreateFromYawPitchRoll(shape.Rotation.Y, shape.Rotation.X, shape.Rotation.Z);
basicEffect.World = worldMatrix;
graphicsDevice.SetVertexBuffer(shape.vertexBuffer);
graphicsDevice.Indices = shape.indexBuffer;
foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) {
pass.Apply();
graphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, shape.vertices.Length / 3);
}
}
}
Could the problem be in the camera?
I am in Visual Studio Code
Monogame version: 3.8.1.303