2010-05-08 98 views
7

我想将我的游戏网格划分为矩形数组。每个矩形都是40x40,每列有14个矩形,共25列。这涵盖了560x1000的游戏区域。使用XNA在游戏窗口中显示矩形

这是我已经设置了使矩形的第一列上的游戏网格代码:

Rectangle[] gameTiles = new Rectangle[15]; 

for (int i = 0; i <= 15; i++) 
{ 
    gameTiles[i] = new Rectangle(0, i * 40, 40, 40); 
} 

我敢肯定这个工作,当然我无法证实,因为矩形不呈现在屏幕上让我身体看到它们。我想为调试目的而做的是渲染边框,或者用颜色填充矩形,以便我可以在游戏本身上看到它,以确保其正常工作。

有没有办法做到这一点?或者任何相对简单的方法,我可以确保它的工作?

非常感谢。

回答

23

首先,白色1x1像素纹理矩形:

var t = new Texture2D(GraphicsDevice, 1, 1); 
t.SetData(new[] { Color.White }); 

现在,你需要渲染矩形 - 假设矩形称为rectangle。对于填充块的渲染,它非常简单 - 确保将色调Color设置为所需的颜色。只需使用此代码:

spriteBatch.Draw(t, rectangle, Color.Black); 

对于边框,是否更复杂。你要画4条线组成的轮廓(这里的矩形r):

int bw = 2; // Border width 

spriteBatch.Draw(t, new Rectangle(r.Left, r.Top, bw, r.Height), Color.Black); // Left 
spriteBatch.Draw(t, new Rectangle(r.Right, r.Top, bw, r.Height), Color.Black); // Right 
spriteBatch.Draw(t, new Rectangle(r.Left, r.Top, r.Width , bw), Color.Black); // Top 
spriteBatch.Draw(t, new Rectangle(r.Left, r.Bottom, r.Width, bw), Color.Black); // Bottom 

希望它能帮助!

+1

+1伟大的答案。正是我正在寻找的!谢谢 – 2010-08-12 00:47:39

+0

+1短而正是我所需要的。 – FRoZeN 2011-08-02 15:30:45

0

如果你想在你现有的纹理上绘制矩形,这就完美了。伟大的,当你想测试/查看碰撞

http://bluelinegamestudios.com/blog/posts/drawing-a-hollow-rectangle-border-in-xna-4-0/

-----从网站-----

的基本技巧,绘制形状是使单个像素纹理是白色,然后您可以与其他颜色混合并以坚固的形状进行显示。

// At the top of your class: 
Texture2D pixel; 

// Somewhere in your LoadContent() method: 
pixel = new Texture2D(GameBase.GraphicsDevice, 1, 1, false, SurfaceFormat.Color); 
pixel.SetData(new[] { Color.White }); // so that we can draw whatever color we want on top of it 
在draw()方法

然后做这样的事情:

spriteBatch.Begin(); 

// Create any rectangle you want. Here we'll use the TitleSafeArea for fun. 
Rectangle titleSafeRectangle = GraphicsDevice.Viewport.TitleSafeArea; 

// Call our method (also defined in this blog-post) 
DrawBorder(titleSafeRectangle, 5, Color.Red); 

spriteBatch.End(); 

这确实绘图的实际方法:

private void DrawBorder(Rectangle rectangleToDraw, int thicknessOfBorder, Color borderColor) 
{ 
    // Draw top line 
    spriteBatch.Draw(pixel, new Rectangle(rectangleToDraw.X, rectangleToDraw.Y, rectangleToDraw.Width, thicknessOfBorder), borderColor); 

    // Draw left line 
    spriteBatch.Draw(pixel, new Rectangle(rectangleToDraw.X, rectangleToDraw.Y, thicknessOfBorder, rectangleToDraw.Height), borderColor); 

    // Draw right line 
    spriteBatch.Draw(pixel, new Rectangle((rectangleToDraw.X + rectangleToDraw.Width - thicknessOfBorder), 
            rectangleToDraw.Y, 
            thicknessOfBorder, 
            rectangleToDraw.Height), borderColor); 
    // Draw bottom line 
    spriteBatch.Draw(pixel, new Rectangle(rectangleToDraw.X, 
            rectangleToDraw.Y + rectangleToDraw.Height - thicknessOfBorder, 
            rectangleToDraw.Width, 
            thicknessOfBorder), borderColor); 
}