Creating a Custom Effect with Texturing

Creating a Custom Effect with Texturing

Demonstrates how to use a custom effect and a texture to render a 3D object.


Complete Sample

The code in the topic shows you the technique for creating an effect to apply a texture. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Using a custom effect and a texture

To use a custom effect and a texture

  1. Create a vertex declaration that contains a position and a texture coordinate.

  2. Create a vertex buffer from the vertex declaration.

    vertexDeclaration = new VertexDeclaration(new VertexElement[]
            new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
            new VertexElement(12, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0)
    vertexBuffer = new VertexBuffer(
  3. Create a custom effect using the Effect class.

  4. Load the Effect object using the ContentManager.Load<Effect> method to load the .fx file.

  5. Load a Texture2D object using the ContentManager.Load<Texture2D> method to load the asset.

  6. Call SetValue to initialize each effect parameter using the corresponding game property.

  7. Initialize the CurrentTechnique to a technique that exists in the .fx file.

    effect = Content.Load<Effect>("ReallySimpleTexture");
    Texture2D texture = Content.Load<Texture2D>("XNA_pow2");
    effect.CurrentTechnique = effect.Techniques["TransformAndTexture"];
  8. Render the effect.

  9. Set the RasterizerState property to turn culling off so that all primitives will be drawn regardless of the order of the vertices.

  10. Loop through each pass in the effect calling DrawPrimitives.

    RasterizerState rasterizerState1 = new RasterizerState();
    rasterizerState1.CullMode = CullMode.None;
    graphics.GraphicsDevice.RasterizerState = rasterizerState1;
    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            0,  // start vertex
            12  // number of primitives to draw

Community Additions

© 2016 Microsoft