2011-06-04 108 views
1

我想在Windows Phone的屏幕上繪製網格;它會幫助我更好地將我的精靈定位在屏幕上,而不是猜測屏幕上的位置。我想在Windows Phone 7上使用XNA繪製網格

我發現使用XNA 3.0網格(2D或3D)的幾個例子,不過不幸的是,架構是不同的,因此在XNA 4.0

代碼does not工作有沒有人有什麼可以工作?

謝謝!

+0

這是一個網格,當你移動你的相機,或者它被應用到你的對象/四邊形等時,在屏幕上是靜態的嗎?你在3d或2d工作?謝謝 – 2011-06-04 03:41:57

+0

謝謝Loyoric。我在2d工作。我正在嘗試使用基元顯示線條(或點)。一旦我學會這樣做,我想在屏幕上顯示一些x,y文本座標。我有一些示例代碼,它是一個for-loops應該繪製所有線,但雖然我有80多個頂點,但只顯示1行。這條線有些問題,但無法弄清楚。 getScreenManager.GraphicsDevice.DrawUserPrimitives (PrimitiveType.LineList,vertices3,0,40); 。我讀過XNA不支持基本的線/圓,所以原始圖很難做到。 – s0ftimage 2011-06-04 03:49:45

+0

好吧,添加更多..我有點工作在2D(這是一個Z平面設置爲0的3D)。 – s0ftimage 2011-06-04 03:51:21

回答

2

你可以在這裏下載PrimitiveBatchhttp://create.msdn.com/en-US/education/catalog/sample/primitives並使用下面的代碼生成一個合適的網格作爲紋理。

PrimitiveBatch primitiveBatch; 
private Texture2D GenerateGrid(Rectangle destRect, int cols, int rows, Color gridColor, int cellSize) 
{ 
    int w = (int)(cols * gridCellSize); 
    int h = (int)(rows * gridCellSize); 

    float uselessWidth = destRect.Width - w; 
    float uselessHeigth = destRect.Height - h; 

    Rectangle bounds = new Rectangle((int)(uselessWidth/2) + destRect.X, (int)(uselessHeigth/2) + destRect.Y, w, h); 

    RenderTarget2D grid = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); 

    GraphicsDevice.SetRenderTarget(grid); 
    GraphicsDevice.Clear(Color.Transparent); 

    primitiveBatch.Begin(PrimitiveType.LineList); 

    float x = bounds.X; 
    float y = bounds.Y; 

    for (int col = 0; col < cols + 1; col++) 
    { 
     primitiveBatch.AddVertex(new Vector2(x + (col * gridCellSize), bounds.Top), gridColor); 
     primitiveBatch.AddVertex(new Vector2(x + (col * gridCellSize), bounds.Bottom), gridColor); 
    } 

    for (int row = 0; row < rows + 1; row++) 
    { 
     primitiveBatch.AddVertex(new Vector2(bounds.Left, y + (row * gridCellSize)), gridColor); 
     primitiveBatch.AddVertex(new Vector2(bounds.Right, y + (row * gridCellSize)), gridColor); 
    } 
    primitiveBatch.End(); 

    GraphicsDevice.SetRenderTarget(null); 
return grid; 
} 
+0

不錯的答案,+1 – 2011-06-07 08:33:39

+0

謝謝,我很高興:) – zavolokas 2011-06-18 16:55:03

1

一個快速和骯髒的方式,你可以做到這一點(因爲它是爲了調試越快越好)是簡單地創建一個與您正在運行XNA遊戲的分辨率相同的網格紋理(如果你是以與手機相同的分辨率運行它,這將是480x800)。大多數紋理將只是一個alpha地圖,並且一個像素的網格線可以創建多個分辨率,或者您可以重複一個單一像素的小紋理,將屏幕的一部分劃分爲您正在運行的分辨率在。

繪製方法將如下所示並被稱爲每一幀。

你的遊戲類

Texture2D gridTexture; 
Rectangle gridRectangle; 

內聲明也代碼此代碼應該是在你的LoadContent方法

//Best to use something like a png file 
gridTexture = content.Load<Texture2D>("pathto/mygridtexture"); 
gridRectangle = new Rectangle(0,0,resolutionX,resolutionY); 

這個方法應該從過去以確保它在頂部您的Draw方法被調用假設你只是使用標準的spriteBatch.Begin()渲染精靈(首先如果你正在做FrontToBack渲染)。

public void DrawGrid() 
{ 
    spriteBatch.Draw(gridTexture, gridRectangle, Color.White); 
} 

該網格將繼續在整個應用程序的運行平穩,並試圖去排隊你的UI或在你的遊戲中的相對位置的對象時應該有用。

HTH。