2013-06-24 105 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

但是,您的定義的頂點和索引是不一致的。繼續之前,你必須糾正這一點。