Making an object transparent

I’m new to Monogame and I want to port my Minecraft clone project from Unity. I want to use effects to make water layers transparent and I wrote this pixel shader:

PixelShaderOutput PixelShaderFunction(VertexShaderOutput input)
{
    PixelShaderOutput output = (PixelShaderOutput)0;

    output.Color = tex2D(textureSampler, input.TexureCoordinate);
 
    output.Color.a =Alpha;
  
      

    return output;
}

I set the value Alpha to 0.7f, trying to make the water semi-transparent, but the water is still solid like this:

the code which draws the terrain is here:

  buffer.SetData(c.verticesWTArray);
  device.SetVertexBuffer(buffer);
  bufferIndex.SetData(c.indicesWTArray);
  device.Indices = bufferIndex;
  basicShader.Parameters["Alpha"].SetValue(0.7f);
  foreach (EffectPass pass in basicShader.CurrentTechnique.Passes)
  {
  pass.Apply();
      device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, c.indicesWTArray.Length / 3);
  }

Is there a property to make the changes of Alpha value bring semi-transparent rendering or is there a way to write a shader which makes transparent object rendering?

All you need is device.BlendState = BlendState.AlphaBlend;

1 Like

That really helped me.Thanks!

1 Like

Since you are not multiplying RGB with alpha in your shader, you will most likely want BlendState.NonPremultiplied

or

output.Color.rgb *= Alpha;
2 Likes

Thanks for your help, my world is more fancy now!
Also, the rendering sequence matters when rendering semi-transparent objects.
We should render all solid objects first, then render transparent objects to avoid depth testing problems.
solid->transparent->solid->transparent… sequence:


solid->solid->…transparent->transparent… sequence:

1 Like

All opaque first, then all transparent sorted back to front. DepthStencilState.Default (read/write) when rendering opaque, DepthStencilState.Read when rendering transparent.

2 Likes

Also you can sort all opaque front to back to avoid overdraw.

If you do that on CPU then do that rather as part of your hierarchy occlusion as otherwise that CPU overhead might get brutal if you truly do that per object. Or go for GPU driven rendering, sort it out on GPU using bitonic sort, then indirect draw and you are golden… however that has some time, right now only thing that really needs to be sorted are transparent objects otherwise he wont get correct result.