我正在尝试使用XNA中的此代码绘制三角形:
VertexPositionColor[] vertices = new VertexPositionColor[3];
vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
vertices[0].Color = Color.Red;
vertices[1].Position = new Vector3(0, 0.5f, 0f);
vertices[1].Color = Color.Green;
vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
vertices[2].Color = Color.Yellow;
GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, vertices, 0, 1);
但是,只要我运行它,应用程序就会关闭,并抛出InvalidOperationException。这是WP7应用程序。我错过了什么吗?感谢您的帮助。
答案 0 :(得分:9)
The documentation表示DrawUserPrimitives
在以下情况下抛出InvalidOperationException
在调用DrawUserPrimitives之前未设置有效的顶点着色器和像素着色器。在执行任何绘制操作之前,必须在设备上设置有效的顶点着色器和像素着色器(或有效效果)。
(它还表示,如果您的顶点无效,它会抛出 - 但它们看起来对我来说没问题。)
您需要在图形设备上设置Effect
。具体而言,您需要在致电EffectPass.Apply
之前致电DrawUserPrimitives
。一个简单的方法是使用BasicEffect
。以下是一些适合放入Draw
方法的代码,用于说明这一点:
// These three lines are required if you use SpriteBatch, to reset the states that it sets
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
// Transform your model to place it somewhere in the world
basicEffect.World = Matrix.CreateRotationZ(MathHelper.PiOver4) * Matrix.CreateTranslation(0.5f, 0, 0); // for sake of example
//basicEffect.World = Matrix.Identity; // Use this to leave your model at the origin
// Transform the entire world around (effectively: place the camera)
basicEffect.View = Matrix.CreateLookAt(new Vector3(0, 0, -3), Vector3.Zero, Vector3.Up);
// Specify how 3D points are projected/transformed onto the 2D screen
basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45),
(float)GraphicsDevice.Viewport.Width / (float)GraphicsDevice.Viewport.Height, 1.0f, 100.0f);
// Tell BasicEffect to make use of your vertex colors
basicEffect.VertexColorEnabled = true;
// I'm setting this so that *both* sides of your triangle are drawn
// (so it won't be back-face culled if you move it, or the camera around behind it)
GraphicsDevice.RasterizerState = RasterizerState.CullNone;
// Render with a BasicEffect that was created in LoadContent
// (BasicEffect only has one pass - but effects in general can have many rendering passes)
foreach(EffectPass pass in basicEffect.CurrentTechnique.Passes)
{
// This is the all-important line that sets the effect, and all of its settings, on the graphics device
pass.Apply();
// Here's your code:
VertexPositionColor[] vertices = new VertexPositionColor[3];
vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
vertices[0].Color = Color.Red;
vertices[1].Position = new Vector3(0, 0.5f, 0f);
vertices[1].Color = Color.Green;
vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
vertices[2].Color = Color.Yellow;
GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, vertices, 0, 1);
}
答案 1 :(得分:-3)
当组件发现它处于意外状态时,通常会抛出该异常(InvalidOperationException)。因此,在您的情况下,请确保在调用DrawUserPrimitives之前,GraphicsDevice不需要设置其他一些属性。