2013-06-24 93 views
0

我已经看了看http://msdn.microsoft.com/en-us/library/bb196414.aspx#ID2EEF 在这里,他们解释了如何利用XNA 2D线,但我得到一个exeption(见脚本)XNA - 绘制二维线

  { 
       int points = 3;//I tried different values(1,2,3,4) 
       VertexPositionColor[] primitiveList = new VertexPositionColor[points]; 

       for (int x = 0; x < points/2; x++) 
       { 
        for (int y = 0; y < 2; y++) 
        { 
         primitiveList[(x * 2) + y] = new VertexPositionColor(
          new Vector3(x * 100, y * 100, 0), Color.White); 
        } 
       } 
       // Initialize an array of indices of type short. 
       short[] lineListIndices = new short[(points * 2) - 2]; 

       // Populate the array with references to indices in the vertex buffer 
       for (int i = 0; i < points - 1; i++) 
       { 
        lineListIndices[i * 2] = (short)(i); 
        lineListIndices[(i * 2) + 1] = (short)(i + 1); 
       } 
       GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
        PrimitiveType.LineList, 
        primitiveList, 
        0, // vertex buffer offset to add to each element of the index buffer 
        8, // number of vertices in pointList 
        lineListIndices, // the index buffer 
        0, // first index element to read 
        7 // number of primitives to draw 
        ); <---This parameter must be a valid index within the array. Parameter name: primitiveCount 
      } 

,但我对如何解决不知道这一点,因为这是我第一次使用3D渲染制作2D图形

背景:

IM做了XNA的2D游戏引擎,我想使一个类绘制简单的数字, 我已经知道你可以使用1x1用于绘制的Texture2D像素技巧,但我也想知道这种方式,因为否则CPU将执行所有计算,而GPU可以轻松处理此问题。

+0

我使用Google本图书馆https://bitbucket.org/C3/2d-xna-primitives/wiki/Home – Dmi7ry

回答

0

由于您确实没有提供任何错误或任何信息,因此我只会告诉您如何绘制它们。

我使用这个扩展方法绘制一条线,你需要一个白色的1x1纹理

public static void DrawLine(this SpriteBatch spriteBatch, Vector2 begin, Vector2 end, Color color, int width = 1) 
{ 
    Rectangle r = new Rectangle((int)begin.X, (int)begin.Y, (int)(end - begin).Length()+width, width); 
    Vector2 v = Vector2.Normalize(begin - end); 
    float angle = (float)Math.Acos(Vector2.Dot(v, -Vector2.UnitX)); 
    if (begin.Y > end.Y) angle = MathHelper.TwoPi - angle; 
    spriteBatch.Draw(Pixel, r, null, color, angle, Vector2.Zero, SpriteEffects.None, 0); 
} 

这也将吸引由点的形状,closed定义所述形状应该关闭或不

public static void DrawPolyLine(this SpriteBatch spriteBatch, Vector2[] points, Color color, int width = 1, bool closed = false) 
    { 


     for (int i = 0; i < points.Length - 1; i++) 
      spriteBatch.DrawLine(points[i], points[i + 1], color, width); 
     if (closed) 
      spriteBatch.DrawLine(points[points.Length - 1], points[0], color, width); 

    } 
0

首先是定义顶点。这看起来有点奇怪。如果points3,那么外环从0..0开始,内环从0..1开始。所以你有两个顶点。这些点只有一条线可以绘制。如果你指定points = 4,那么你实际上有四点。

看来你想绘制一个连续的线,没有重复的顶点。所以你并不需要索引表示(带索引缓冲区)。一个接一个地指定顶点就足够了。

为了绘制一条连续的线,您应该使用PrimitiveType.LineStrip。这会自动将顶点与线连接起来。所以你需要points - 1指数(如果你真的想使用它们)。

在调用DrawUserIndexedPrimitives()有一些错误的观点认为导致异常:

  1. 你说顶点的数量是8,这肯定是不正确的。这是(points/2) * 2
  2. 你说基元数是7,这也不是真的。这应该是points - 1

但是,您的定义的顶点和索引是不一致的。继续之前,你必须纠正这一点。