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

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

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

非常感谢。

4

2 回答 2

23

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

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

希望能帮助到你!

于 2010-05-08T22:28:42.073 回答
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);
}
于 2013-12-01T05:38:10.910 回答