简体   繁体   中英

Drawing a Mesh and a Texture 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 a png) on the screen, using libgdx.

When I run this, I can only see the Texture (circle) on the screen. What should I do in order to make both Mesh and the Texture visible ?

SpriteBatch uses orthographic projection matrix. When you call batch.begin() then it applies its matrices (see SpriteBatch.setupMatrices().

So either:

  1. change vertices for mesh, so it is on screen:

     mesh.setVertices(new float[] { 100f, 100f, 0, 400f, 100f, 0, 250, 400f, 0 }); 
  2. move rendering of mesh 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 matrices set by batch in begin(); because SpriteBatch.end() doesn't set matrices back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM