# Change opacity of a texture in XNA 4.0

I have created a terrain using VertexPositionNormalTexture in XNA 4.0, but now I would like to allow the user changing the opacity of the terrain (from 0%, totally opaque, to 100%, totally transparent), so that user can see through it. Is there a simple way to do that?

I would also like to know how to do that if I use VertexPositionColor instead of VertexPositionNormalTexture (i.e., creating a colored terrain)

Thank you very much in advance.

• Im assuming this is 3D, but to make transparent 2D textures, in the spriteBatch.Draw() method, change the color value to Color.White *= 0.5f. that'll give you half transparency. Mar 6 '13 at 13:01
• Yes, it's 3D. I knew that I could change it with SpriteBatch, but I am using DrawIndexedPrimitives of GraphicsDevice... Mar 6 '13 at 13:44
• Do you want to change the entire terrain's opacity or only sections of it? If it's the latter then you can easily accomplish this using an alpha map. Mar 6 '13 at 15:31

Changing the colours of a vertex buffer is relatively expensive. You'd have to use something like VertexPositionColor and then modify every vertex every time you want to change transparency!

It would be much easier, and faster, to add transparency using a shader (pixel or vertex). Fortunately BasicEffect does exactly what you need - it even has an appropriate Alpha member. Here's the code:

GraphicsDevice.BlendState = BlendState.AlphaBlend;
basicEffect.Alpha = 0.5f; // <- however opaque you want it


The other built-in effects also have Alpha members.

If you're writing your own shaders - just pass in a colour (with appropriate transparency) as a shader parameter. Then somewhere in your vertex or pixel shader, multiply by that colour before output.

• Perfect, that was I was looking for. Previously, I was using Riemer's effects file, but BasicEffect has the Alpha variable, which is perfect for me... Sadly, now I am having lightning and colour problems with BasicEffect, but I imagine it's something related to the effect's configuration. Thanks!! Mar 6 '13 at 16:24
• Just adding EnableDefaultLighting() should get some lighting working, so you can test with it. It seems to work correctly with Alpha. Perhaps there's a problem with your model's normals? Mar 6 '13 at 18:12
• I don't think so... please, take a look at this question I have posted today: gamedev.stackexchange.com/questions/50592/… I still don't have enough reputation to post more than 2 links, so if you want a more complete question, look at stackoverflow.com/questions/15269216/xna-4-0-weird-color-error Mar 7 '13 at 10:55