Seven textures for 3D development in Windows Phone

Source: Internet
Author: User

After learning the previous sections, we have made the object have three major motion capabilities: translation, scaling, and rotation. Through combined use, we can form a complex object motion model.

Next, we will add some colors to the object and change the gray world.

Do you still remember the triangle data we previously defined? The definition was as follows:

Triangle = new vertexpositioncolor [] {

New vertexpositioncolor (New vector3 (0, 1, 0), color. Red ),

New vertexpositioncolor (New vector3 (1,-1, 0), color. Green ),

New vertexpositioncolor (New vector3 (-1,-1, 0), color. Blue)

};

We use an array of vertexpositioncolor objects, which uses coordinates and color values to represent a vertex. However, before that, the color value never worked. We can see all the white triangles, in fact, it is very easy to make the color take effect. You just need to add the following sentence in the draw () method:

Basiceffect. vertexcolorenabled = true;

After a run, the beautiful triangle will come out.


However, it is obvious that only colors cannot be used to make more realistic objects, such as wood triangles. At this time, what we need is to use textures, that is, to use wood grain images attached to triangles, and eventually become the desired effect.

In Windows Phone, the texture is represented by the texture2d class. The most common one is to represent an image in the resource. The actual situation is to upload an image in the contentproject, such as a wood.jpg image in the hellocontentproject. Then, in the loadcontent () method, you can use the following statement to represent the image as a texture2d object.

Texture = content. Load <texture2d> (@ "Wood ");

With texture, we must have correct texture coordinates, which are called UV coordinates. The UV coordinates of a texture image are defined as follows:

 

In this way, we can specify the texture positions of different vertices. For example, the UV coordinate of the top vertex of the triangle is (0.5, 0), the lower-left vertex is (), and the lower-right vertex is ). For triangles that require texture coordinates, the vertexpositioncolor type used previously is not enough. We need to use the vertexpositiontexture type, that is, each vertex is described using coordinates and texture coordinates, instead of describing coordinates and colors. The corresponding triangle data is as follows:

Triangle = newvertexpositiontexture [] {

New vertexpositiontexture (newvector3 (0, 1, 0), new vector2 (0.5f, 0 )),

New vertexpositiontexture (newvector3 (1,-1, 0), new vector2 (1, 1 )),

New vertexpositiontexture (newvector3 (-1,-1, 0), new vector2 (0, 1 ))

};

Finally, to get the rendering result, modify the draw () method and adjust the texture attribute of basiceffect:

Basiceffect. textureenabled = true;

Basiceffect. Texture = texture;

Run the program to get a triangle with wood grain.


Complete source code for the game1 class is provided in this section:


public class Game1: Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        Camera camera;
        Matrix world = Matrix.Identity;
        BasicEffect basicEffect;
        VertexPositionTexture [] triangle;
        Matrix translateMatrix = Matrix.Identity;
        Matrix scaleMatrix = Matrix.CreateScale (0.5f);
        Matrix rotateMatrix = Matrix.Identity;
        Texture2D texture;

        public Game1 ()
        {
            graphics = new GraphicsDeviceManager (this);
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks (333333);

            // Extend battery life under lock.
            InactiveSleepTime = TimeSpan.FromSeconds (1);
            graphics.IsFullScreen = true;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content. Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </ summary>
        protected override void Initialize ()
        {
            // TODO: Add your initialization logic here

            base.Initialize ();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </ summary>
        protected override void LoadContent ()
        {
            camera = new Camera (this, new Vector3 (0, 0, 5), Vector3.Zero, Vector3.Up, MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 1.0f, 50.0f);
            Components.Add (camera);
            basicEffect = new BasicEffect (GraphicsDevice);
            triangle = new VertexPositionTexture [] {
                new VertexPositionTexture (new Vector3 (0, 1, 0), new Vector2 (0.5f, 0)),
                new VertexPositionTexture (new Vector3 (1, -1, 0), new Vector2 (1,1)),
                new VertexPositionTexture (new Vector3 (-1, -1, 0), new Vector2 (0,1))
            };

            texture = Content.Load <Texture2D> (@ "wood");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </ summary>
        protected override void UnloadContent ()
        {
            // TODO: Unload any non Content Manager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </ summary>
        /// <param name = "gameTime"> Provides a snapshot of timing values. </ param>
        protected override void Update (GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState (PlayerIndex.One) .Buttons.Back == ButtonState.Pressed)
                this.Exit ();

            TouchPanel.EnabledGestures = GestureType.Tap;
            if (TouchPanel.IsGestureAvailable)
            {
                GestureSample gestureSample = TouchPanel.ReadGesture ();
                if (gestureSample.GestureType == GestureType.Tap)
                {
                    translateMatrix * = Matrix.CreateTranslation (0.3f, 0, 0);
                    // scaleMatrix = Matrix.CreateScale (0.9f);
                    rotateMatrix * = Matrix.CreateRotationY (MathHelper.ToRadians (10));
                }
            }

            base.Update (gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </ summary>
        /// <param name = "gameTime"> Provides a snapshot of timing values. </ param>
        protected override void Draw (GameTime gameTime)
        {
            GraphicsDevice.Clear (Color.CornflowerBlue);
            RasterizerState rasterizerState = new RasterizerState ();
            rasterizerState.CullMode = CullMode.None;
            GraphicsDevice.RasterizerState = rasterizerState;

            basicEffect.World = scaleMatrix * translateMatrix * rotateMatrix;
            basicEffect.View = camera.view;
            basicEffect.Projection = camera.projection;

            basicEffect.TextureEnabled = true;
            basicEffect.Texture = texture;
            GraphicsDevice.SamplerStates [0] = SamplerState.PointClamp;
            
            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply ();
                GraphicsDevice.DrawUserPrimitives <VertexPositionTexture> (PrimitiveType.TriangleStrip, triangle, 0, 1);
            }

            base.Draw (gameTime);
        }
    } 


-- Welcome to reprint, please indicate the source of http://blog.csdn.net/caowenbin --

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.