在XNA游戏窗口中显示矩形

7
我希望将我的游戏网格分成一个矩形数组。每个矩形的大小为40x40,每列有14个矩形,总共有25列。这覆盖了一个560x1000的游戏区域。
这是我设置的用于制作游戏网格第一列矩形的代码:
Rectangle[] gameTiles = new Rectangle[15];

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

我很确定这个方法是可行的,但是因为矩形无法在屏幕上渲染出来让我看到,所以我不能确认它是否有效。为了调试目的,我想渲染一个边框,或者用颜色填充矩形,这样我就可以在游戏中看到它,以确保它能正常工作。
有没有办法实现这个功能?或者有没有相对简单的方法来确保它能正常工作?
非常感谢。
2个回答

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

希望能对您有所帮助!

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接