How to draw triangles, lines etc in XNA?
user primitives are the ones that DON’T need a vertex buffer
Here’s how. This example isn’t commented, but if you’re familiar with OpenGL and glVertex3f and glColor3f, this should make a lot of sense to you!
Copy and paste into a new XNA project. There is a Main method here already, so you’ll need to delete the one that comes with your XNA project.
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
class G : Game
{
GraphicsDeviceManager g;
BasicEffect r;
Vector3 eye = new Vector3( 2, 2, 2 ); // put the user @ (2,2,2)
Vector3 look = new Vector3( 0, 0, 0 ) ; // have him stare into the origin.
Vector3 up = new Vector3( 0, 1, 0 ) ; // define UP as +y.
VertexPositionColor[] tris = new VertexPositionColor[ 3 ];
VertexPositionColor[] axisLines = new VertexPositionColor[ 6 ]; // 6 verts for axis lines
public G()
{
g = new GraphicsDeviceManager( this );
}
protected override void LoadContent()
{
r = new BasicEffect( GraphicsDevice, null );
r.VertexColorEnabled = true;
// Set up vertices. Remember d3d wants clockwise.
tris[ 0 ] = new VertexPositionColor( new Vector3( -0.5f, -0.25f, 0 ), Color.Black );
tris[ 1 ] = new VertexPositionColor( new Vector3( 0, 0.5f, 0 ), Color.GreenYellow );
tris[ 2 ] = new VertexPositionColor( new Vector3( 0.5f, -0.25f, 0 ), Color.Red );
int axisLength = 2 ;
axisLines[ 0 ] = new VertexPositionColor( -axisLength * Vector3.UnitX, Color.Red );
axisLines[ 1 ] = new VertexPositionColor( axisLength * Vector3.UnitX, Color.Red );
axisLines[ 2 ] = new VertexPositionColor( -axisLength * Vector3.UnitY, Color.Green );
axisLines[ 3 ] = new VertexPositionColor( axisLength * Vector3.UnitY, Color.Green );
axisLines[ 4 ] = new VertexPositionColor( -axisLength * Vector3.UnitZ, Color.Blue );
axisLines[ 5 ] = new VertexPositionColor( axisLength * Vector3.UnitZ, Color.Blue );
}
protected override void Draw( GameTime gameTime )
{
GraphicsDevice.Clear( Color.Black );
GraphicsDevice.RenderState.CullMode = CullMode.None ; // don't discard
// triangles that are ccw. d3d has opposite winding order (cw) than openGL.
// Set look.
r.View = Matrix.CreateLookAt( eye, look, up );
r.Projection = Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), 1.0f, 1.0f, 1000.0f ) ;
r.GraphicsDevice.VertexDeclaration = new VertexDeclaration( GraphicsDevice, VertexPositionColor.VertexElements ) ;
r.Begin();
foreach( EffectPass pass in r.CurrentTechnique.Passes )
{
pass.Begin();
r.GraphicsDevice.DrawUserPrimitives( PrimitiveType.TriangleList, tris, 0, 1 );
r.GraphicsDevice.DrawUserPrimitives( PrimitiveType.LineList, axisLines, 0, 3 );
pass.End();
}
r.End();
base.Draw( gameTime );
}
static void Main( string[] args )
{
G game = new G();
game.Run();
}
}
One Comment
i am planning to do a projet based on basic primitives using opengl so can i have description about basic primitives
One Trackback/Pingback
[...] About MECG 1CG 2INDEX « Drawing basic user primitives in XNA drawing basic primitives in xna [...]