c# - 使用 XNA 绘制矩形

标签 c# optimization xna

我正在开发游戏。我想在发生某些事情时突出显示屏幕上的一个点。

我创建了一个类来为我做这件事,并找到了一些代码来绘制矩形:

static private Texture2D CreateRectangle(int width, int height, Color colori)
{
    Texture2D rectangleTexture = new Texture2D(game.GraphicsDevice, width, height, 1, TextureUsage.None,
    SurfaceFormat.Color);// create the rectangle texture, ,but it will have no color! lets fix that
    Color[] color = new Color[width * height];//set the color to the amount of pixels in the textures
    for (int i = 0; i < color.Length; i++)//loop through all the colors setting them to whatever values we want
    {
        color[i] = colori;
    }
    rectangleTexture.SetData(color);//set the color data on the texture
    return rectangleTexture;//return the texture
}

问题在于上面的代码在每次更新时都会被调用(每秒 60 次),而且编写时并未考虑优化。它需要非常快(上面的代码卡住了游戏,现在只有骨架代码)。

有什么建议吗?

注意:任何新代码都会很棒(线框/填充都可以)。我希望能够指定颜色。

最佳答案

SafeArea demo XNA Creators Club 网站上有专门执行此操作的代码。

您不必每帧都创建纹理,只需在 LoadContent 中创建。该演示中代码的精简版本:

public class RectangleOverlay : DrawableGameComponent
{
    SpriteBatch spriteBatch;
    Texture2D dummyTexture;
    Rectangle dummyRectangle;
    Color Colori;

    public RectangleOverlay(Rectangle rect, Color colori, Game game)
        : base(game)
    {
        // Choose a high number, so we will draw on top of other components.
        DrawOrder = 1000;
        dummyRectangle = rect;
        Colori = colori;
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        dummyTexture = new Texture2D(GraphicsDevice, 1, 1);
        dummyTexture.SetData(new Color[] { Color.White });
    }

    public override void Draw(GameTime gameTime)
    {
        spriteBatch.Begin();
        spriteBatch.Draw(dummyTexture, dummyRectangle, Colori);
        spriteBatch.End();
    }
}

关于c# - 使用 XNA 绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2792694/

相关文章:

针对大量类实例的 C# 优化

language-agnostic - 尽早规划效率与过早优化

c# - 如何获取显示分辨率(屏幕尺寸)?

c# - 将许多单元的 A* 路径拆分为单独的游戏框架

c# - 消息框模式

c# - 如何在 Blazor 服务器端注销?

c# - 在 C# 中键入右大括号后,如何自动将光标定位在方法大括号之间?

c# - 从旧页面到新页面的多个 301 重定向的最佳实践

python - 优化python编码功能

c# - 使用 c# 和 xna 在单独的类中加载 texture2D