Warning: uncommented
A lot of the time people starting in XNA want to get a grip of things and just DRAW A TRIANGLE. Unfortunately a lot of the MSDN examples don’t show you how to do that, and they jump straight into VertexBuffer and stuff like this without just showing the user the sort of equivalent of just plain old glVertex3f() and glColor3f() calls.
This example is pretty much the equivalent of d3d hello world. Its the most basic way to draw and its not computationally efficient at all (it is more efficient to use vertex buffers!). But it is a nice starting point and lets you get something on the screen right away.
Also notice that it isn’t really 3d. This is speaking to the graphics card barebones.. to make it look 3d, you need a few transformation matrices. You’ll notice here that it won’t draw anything out side of this “canonical view volume” box: (-1,-1,-1) to (1,1,0). That is what the GPU draws in reality. Everything else isn’t drawn.
If you want to see perspective in action in less than 80 lines of code, check this example out.
Anyway, enjoy!
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
class G : Game
{
GraphicsDeviceManager g;
BasicEffect r;
public G()
{
g = new GraphicsDeviceManager( this );
}
protected override void LoadContent()
{
r = new BasicEffect( GraphicsDevice, null );
r.VertexColorEnabled = true;
}
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.
r.GraphicsDevice.VertexDeclaration = new VertexDeclaration( GraphicsDevice, VertexPositionColor.VertexElements ) ;
r.Begin();
foreach( EffectPass pass in r.CurrentTechnique.Passes )
{
pass.Begin();
VertexPositionColor[] tris = new VertexPositionColor[ 3 ];
// 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 );
r.GraphicsDevice.DrawUserPrimitives( PrimitiveType.TriangleList, tris, 0, 1 );
pass.End();
}
r.End();
base.Draw( gameTime );
}
static void Main( string[] args )
{
G game = new G();
game.Run();
}
}