XNA-3D-繪製立方體

一.要點

繪製立方體(或其他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: }
發佈了9 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章