【问题标题】:Healthy way of drawing grid lines in LibGdx在 LibGdx 中绘制网格线的健康方式
【发布时间】:2014-06-14 00:34:59
【问题描述】:

所以,我想在我的游戏中画一个网格,当我写出来的时候,就效率而言(至少对我而言)似乎非常不寻常。我在用于渲染游戏的 render 方法中有两个 for 循环,因此它被调用得非常频繁且快速。

这个 ShapeRenderer 部分是危险信号吗?

public void render(float deltaTime) {
    Gdx.gl.glClearColor(Color.GRAY.r, Color.GRAY.g, Color.GRAY.b, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);       

    batch.begin();
    this.world.getPlayer().render(deltaTime, batch);
    batch.end();

    // Gridlines
    shape.begin(ShapeType.Line);
    shape.setColor(Color.BLACK);
    for (int i = 0; i < Gdx.graphics.getHeight() / 32; i++) {
        shape.line(0, i * 32, Gdx.graphics.getWidth(), i * 32);
    }
    for (int i = 0; i < Gdx.graphics.getWidth() / 32; i++) {
        shape.line(i * 32, 0, i * 32, Gdx.graphics.getHeight());
    }
    shape.end();
}

【问题讨论】:

  • 这并不像它可能的那么糟糕......你可以有两个嵌套循环使其成为O(N^2)而不是O(2*N)。但是,如果此 shape 对象的 line (...) 函数转换为每次调用的绘图调用,则效率可能不高。底层GL_LINES 原语以点对的形式绘制unconnected 线段。如果它真的困扰您,您可以使用顶点列表(索引绘图)轻松地将其简化为单个绘图调用。
  • 老实说,即使您使用了像GL_LINE_STRIP 这样的连接线图元,您仍然可以将其折叠成一个绘图调用。它只需要按照你画线的顺序稍微复杂一点。
  • 如果它没有出现在基准测试或分析中,那么您无需担心。
  • 好的,谢谢大家!我会研究选项。

标签: java opengl libgdx rendering game-engine


【解决方案1】:

您可以使用快速、简单且功能强大的ImmediateModeRenderer20。 请使用 PerspectiveCamera 查看以下代码:

// init primitive renderer
ImmediateModeRenderer20 lineRenderer = new ImmediateModeRenderer20(false, true, 0);

// create atomic method for line
public static void line(float x1, float y1, float z1,
                        float x2, float y2, float z2,
                        float r, float g, float b, float a) {
    lineRenderer.color(r, g, b, a);
    lineRenderer.vertex(x1, y1, z1);
    lineRenderer.color(r, g, b, a);
    lineRenderer.vertex(x2, y2, z2);
}

// method for whole grid
public static void grid(int width, int height) {
    for (int x = 0; x <= width; x++) {
        // draw vertical
        line(x, 0, 0,
                x, 0, -height,
                0, 1, 0, 0);
    }

    for (int y = 0; y <= height; y++) {
        // draw horizontal
        line(0, 0, -y,
                width, 0, -y,
                0, 1, 0, 0);
    }
}

// init 3d camera
PerspectiveCamera perspectiveCamera = new PerspectiveCamera(55, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

// your render loop {
perspectiveCamera.update();
lineRenderer.begin(perspectiveCamera.combined, GL30.GL_LINES);
//... lineRenderer works a lot
grid(10, 10);
//... lineRenderer works a lot
lineRenderer.end();
//}

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 2016-07-21
    • 2022-08-19
    相关资源
    最近更新 更多