Java – Drawing meshes and textures libgdx

Drawing meshes and textures libgdx… here is a solution to the problem.

Drawing meshes and textures libgdx

  private Mesh mesh;
  private Texture texture;

private SpriteBatch batch;

@Override
  public void create() {
    if (mesh == null) {
      mesh = new Mesh(true, 3, 3, new VertexAttribute(Usage.Position, 3,
          "a_position"));

mesh.setVertices(new float[] { -0.5f, -0.5f, 0, 
          0.5f, -0.5f, 0, 
          0, 0.5f, 0 });

mesh.setIndices(new short[] { 0, 1, 2 });

texture = new Texture(Gdx.files.internal("data/circle.png"));

batch = new SpriteBatch();
    }

}

@Override
  public void render() {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

batch.begin();

mesh.render(GL10.GL_TRIANGLES, 0, 3);
    batch.draw(texture, 10, 10);

batch.end();

}

I’m trying to draw a triangle and a circle (from PNG) on the screen using libgdx.

When I run it, I can only see textures (circles) on the screen. What should I do to make both meshes and textures visible?

Solution

SpriteBatch uses an orthogonal projection matrix. When you call batch.begin(), it applies its matrix (see SpriteBatch.setupMatrices().

So either:

  1. Change the vertices of the mesh so that they appear on the screen:

    mesh.setVertices(new float[] { 100f, 100f, 0, 
              400f, 100f, 0, 
              250, 400f, 0 });
    
  2. Move mesh rendering out of batch rendering:

    Gdx.gl10.glMatrixMode(GL10.GL_PROJECTION);
    Gdx.gl10.glLoadIdentity();
    Gdx.gl10.glMatrixMode(GL10.GL_MODELVIEW);
    Gdx.gl10.glLoadIdentity();
    mesh.render(GL10.GL_TRIANGLES, 0, 3);
    
    batch.begin();
    batch.draw(texture, 10, 10);
    batch.end();
    

    You have to reset the projection and transformation matrix set in batches in begin(); Because SpriteBatch.end() does not set the matrix.

Related Problems and Solutions