Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libgdx - ShapeRenderer in Group.draw renders in wrong colour

MyGroup:

public class GShape extends Group{
private ShapeRenderer shape;

public GShape() {
    super();
    shape = new ShapeRenderer();
}

@Override
public void draw(SpriteBatch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);
    shape.begin(ShapeType.Line);
    Gdx.gl10.glLineWidth(5);
    shape.setColor(1, 1f, 1f, 1f);
    shape.line(0, 0, 200, 100);
    shape.end();
}
}

Main:

public class GameControl implements ApplicationListener {
private Stage stage;
private GShape gShape;

@Override
public void create() {
    stage = new Stage(480,320,false);

    Texture t = new Texture(Gdx.files.internal("data/the200.png"));
    Image i = new Image(t);
    stage.addActor(i);
    gShape = new GShape();
    stage.addActor(gShape);
}

@Override
public void dispose() {
}

@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    stage.draw();
//  gShape.render();
}

@Override
public void resize(int width, int height) {
}

@Override
public void pause() {
}

@Override
public void resume() {
}
} 

Colour of shape is not white? Why?

http://nw7.upanh.com/b3.s38.d3/352dd792eb77ce6df204a7af47ae1ac6_55348087.cos.jpg?rand=0.19125773780979216

like image 757
Hoàng Phương Avatar asked Dec 11 '22 15:12

Hoàng Phương


1 Answers

You are probably getting inconsistent results because you're mixing SpriteBatch and ShapeRenderer contexts. Both of these expect state they "store" in OpenGL to be maintained between begin() and end() calls.

The Actor draw() method is called in a context where the SpriteBatch begin() has already been called, so you need to end it before beginning your ShapeRenderer. (And you need to restart the SpriteBatch before returning.

Like this:

@Override
public void draw(SpriteBatch batch, float parentAlpha) {
  super.draw(batch, parentAlpha);
  batch.end();   //  ** End the batch context
  shape.begin(ShapeType.Line);
  // .. draw lines ...
  shape.end()
  batch.begin(); // ** Restart SpriteBatch context that caller assumes is active
}
like image 78
P.T. Avatar answered Feb 16 '23 05:02

P.T.