XNA-3D-绘制三角形

一.在3D空间中绘制三角形

1.新建XNA Windows Game项目,添加成员变量:

  1: VertexPositionColor[] vertices;
  2: VertexBuffer vertexBuffer;
  3: 
  4: BasicEffect basicEffect;
  5: Matrix world;
  6: Matrix view;
  7: Matrix projection;

2.在Initialize()方法中初始化三角形顶点坐标和World,View,Projection矩阵:

  1: vertices = new VertexPositionColor[]
  2: {
  3: 	new VertexPositionColor(new Vector3(0,1,0),Color.Red),
  4: 	new VertexPositionColor(new Vector3(1,-1,0),Color.Green),
  5: 	new VertexPositionColor(new Vector3(-1,-1,0),Color.Blue)				
  6: };
  7: vertexBuffer = new VertexBuffer(GraphicsDevice,
  8: 	typeof(VertexPositionColor),
  9: 	vertices.Length,
 10: 	BufferUsage.None);
 11: vertexBuffer.SetData<VertexPositionColor>(vertices);
 12: GraphicsDevice.SetVertexBuffer(vertexBuffer);
 13: 
 14: world = Matrix.Identity;
 15: view = Matrix.CreateLookAt(new Vector3(0, 0, 5), Vector3.Zero, Vector3.Up);
 16: projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
 17: 	GraphicsDevice.Viewport.AspectRatio,
 18: 	1f,
 19: 	100f);
 20: 
 21: basicEffect = new BasicEffect(GraphicsDevice);
 22: basicEffect.VertexColorEnabled = true;

3.在Draw()方法中绘制三角形:

  1: basicEffect.World = world;
  2: basicEffect.View = view;
  3: basicEffect.Projection = projection;
  4: 
  5: foreach (var pass in basicEffect.CurrentTechnique.Passes)
  6: {
  7: 	pass.Apply();
  8: 	GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(
  9: 		PrimitiveType.TriangleList,
 10: 		vertices,
 11: 		0,
 12: 		1);
 13: }

4.运行结果:

ScreenShot00095

二.坐标变换

在Update()方法中响应键盘按键事件,进行坐标变换:

  1: KeyboardState keyboardState = Keyboard.GetState();
  2: if (keyboardState.IsKeyDown(Keys.R))
  3: {
  4: 	Matrix rototeZ = Matrix.CreateRotationZ(MathHelper.PiOver4);
  5: 	world *= rototeZ;
  6: }
  7: else if (keyboardState.IsKeyDown(Keys.Left))
  8: {
  9: 	Matrix translateLeft = Matrix.CreateTranslation(new Vector3(-0.25f, 0, 0));
 10: 	world *= translateLeft;
 11: }
 12: else if (keyboardState.IsKeyDown(Keys.Right))
 13: {
 14: 	Matrix translateRight = Matrix.CreateTranslation(new Vector3(0.25f, 0, 0));
 15: 	world *= translateRight;
 16: }

三.小技巧

如果需要设置窗口的初始大小,可以在Game类的构造器中修改属性:

  1: graphics.PreferredBackBufferWidth = 400;
  2: graphics.PreferredBackBufferHeight = 300;

posted on 2010-06-19 11:29  wudong  阅读(817)  评论(0编辑  收藏  举报

导航