使用XNA在游戏窗口中显示矩形

我想将我的游戏网格划分为一个矩形arrays。 每个矩形为40×40,每列有14个矩形,总共25列。 这涵盖了560×1000的游戏区域。

这是我设置的代码,用于在游戏网格上创建第一列矩形:

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

我很确定这是有效的,但当然我无法确认它,因为矩形不会在屏幕上呈现让我亲身看到它们。 我想为调试目的做的是渲染边框,或用颜色填充矩形,这样我就可以在游戏本身上看到它,只是为了确保它有效。

有没有办法让这种情况发生? 或者任何相对简单的方法,我可以确保这有效吗?

非常感谢你。

首先,为矩形制作1×1像素的白色纹理:

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

现在,您需要渲染矩形 – 假设Rectangle被称为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 

希望能帮助到你!

如果要在现有纹理上绘制矩形,这非常有用。 想要测试/查看碰撞时非常棒

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); }