XNA-3D-绘制立方体

来源:互联网 发布:api函数与c语言 编辑:程序博客网 时间:2024/05/05 21:43
一.要点

绘制立方体(或其他3D图形)的方法与绘制三角形的方法类似,任何一个3D图形的轮廓都有一系列三角形构成.为减少数据冗余,在绘制复杂3D图形时,应使用

GraphicsDevice.DrawIndexedPrimitives()方法,而不是绘制三角形时所使用的GraphicsDevice.DrawUserPrimitives()。

二.实现代码

1.为Game类添加成员变量:

  1: VertexPositionColor[] vertexList;
  2: VertexBuffer vertexBuffer;
  3: ushort[] indexList;
  4: IndexBuffer indexBuffer;


2.在LoadContent()方法中定义立方体六个顶点的坐标



  1: vertexList = new VertexPositionColor[]
  2: {
  3: new VertexPositionColor(new Vector3(1f,1f,-1f),Color.Red),
  4: new VertexPositionColor(new Vector3(1f,-1f,-1f),Color.Red),
  5: new VertexPositionColor(new Vector3(-1f,-1f,-1f),Color.Red),
  6: new VertexPositionColor(new Vector3(-1f,1f,-1f),Color.Red),
  7: new VertexPositionColor(new Vector3(1f,1f,1f),Color.Red),
  8: new VertexPositionColor(new Vector3(1f,-1f,1f),Color.Red),
  9: new VertexPositionColor(new Vector3(-1f,-1f,1f),Color.Red),
 10: new VertexPositionColor(new Vector3(-1f,1f,1f),Color.Red)
 11: };
 12: vertexBuffer = new VertexBuffer(
 13: GraphicsDevice,
 14: typeof(VertexPositionColor),
 15: vertexList.Length,
 16: BufferUsage.None);
 17: vertexBuffer.SetData<VertexPositionColor>(vertexList);


3.定义顶点索引数组:



  1: indexList = new ushort[]
  2: {
  3: 0,1,2,0,2,3,
  4: 7,4,5,7,5,6,
  5: 0,1,5,0,5,4,
  6: 7,3,2,7,2,6,
  7: 0,4,7,0,7,3,
  8: 2,1,5,2,5,6
  9: };
 10: indexBuffer = new IndexBuffer(
 11: GraphicsDevice,
 12: typeof(ushort),
 13: indexList.Length,
 14: BufferUsage.None);
 15: indexBuffer.SetData<ushort>(indexList);


4.在Draw()方法中添加绘制代码:



  1: GraphicsDevice.SetVertexBuffer(vertexBuffer);
  2: GraphicsDevice.Indices = indexBuffer;
  3: 
  4: int primitiveCount = indexList.Length / 3;
  5: foreach (var pass in basicEffect.CurrentTechnique.Passes)
  6: {
  7: pass.Apply();
  8: GraphicsDevice.DrawIndexedPrimitives(
  9: PrimitiveType.TriangleList,
 10: 0,
 11: 0,
 12: vertexList.Length,
 13: 0,
 14: primitiveCount);
 15: }