In the previous section, we made the object have the most basic movement of translation and scaling. Now let's look at the rotation of one of the three major movements.
As in the previous section, to rotate an object, you only need to multiply it by a matrix on the corresponding coordinate axis. There are three methods to construct the matrix:
Matrix createrotationx (float radians );
Matrix createrotationy (floatradians );
Matrix createrotationz (float radians );
Represents the Rotation Angle on the X, Y, and Z axes. radians represent radians. If you want to use an angle we are familiar with, you can use mathhelper. toradians (10) for conversion.
In addition to rotating along the coordinate axis, there is also a kind of rotation using the yaw, tumble, and pitching representation of the aircraft. The matrix construction method used is as follows:
Matrix createfromyawpitchroll (float yaw, float pitch, float roll );
If you are interested, you can study by yourself.
Continue with the xNa project we created in the previous lesson and open the project in vs2010. Open the game1.cs file and modify the game1 class. Add a member variable to it, representing the rotation matrix:
Matrix rotatematrix = matrix. identity;
At the same time, to facilitate observation, we will use the scalematrix value in the previous section to scale 0.5 times:
Matrixs calematrix = matrix. createscale (0.5f );
Then, modify the world attribute of the basiceffect object in the draw () method:
Basiceffect. World = scalematrix * translatematrix * rotatematrix;
Remove the changes to scalematrix in the update () method and add the handling of rotatematrix:
// Scalematrix = matrix. createscale (0.9f );
Rotatematrix * = matrix. createrotationz (mathhelper. toradians (10 ));
That is, a 10-degree rotation is generated every time you click the screen.
Run the program and observe the rotating result. Then try
Basiceffect. World = scalematrix * translatematrix * rotatematrix;
Change
Basiceffect. World = scalematrix * rotatematrix * translatematrix;
To observe the impact on rotation. It can be seen that the former is first translated along the X of the object, and then rotated according to the Z axis of the position where the translation is located, resulting in a motion like a screw. The latter is first rotated along the Z axis, and then moved along the X axis, resulting in the simultaneous rotation of one side to the right side of the screen and the rotation around its Z axis. Therefore, be careful when handling matrix operations in actual projects.
In addition, you can modify the code to observe the Rotation along the X and Y axes.
When we let the triangle rotate around the Y axis, we will find a strange phenomenon. As the object rotates, when the back of the object faces us, we will not see it. In fact, this is the optimization settings of the rendering engine, because the back of the object is actually not rendered, that is, the back is often called invisible. If you need to pay attention to it, you can find relevant information, to cancel the backend hiding option, you only need to modify the raster parameter of graphicsdevice, that is, add the following code to the draw () method:
Graphicsdevice. Clear (color. cornflowerblue );
Rasterizerstate = new rasterizerstate ();
Rasterizerstate. cullmode = cullmode. None;
Graphicsdevice. rasterizerstate = rasterizerstate;
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; VertexPositionColor[] triangle; Matrix translateMatrix=Matrix.Identity; Matrix scaleMatrix = Matrix.CreateScale(0.5f); Matrix rotateMatrix = Matrix.Identity; 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 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) }; } /// <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 ContentManager 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; foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) { pass.Apply(); GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, triangle, 0, 1); } base.Draw(gameTime); } }
-- Welcome to reprint, please indicate the source of http://blog.csdn.net/caowenbin --