screen - Libgdx background and foreground in single stage -
my requirements:
- background filling entire physical screen (stretching if required)
- preserve aspect ratio of foreground assets (work virtual width , height)
for this, use 2 stages in screen shown in code below.
public void render(float delta) { backgroundstage.act(delta); backgroundstage.draw(); foregroundstage.act(delta); foregroundstage.draw(); } public void resize(int width, int height) { background.setwidth(width); background.setheight(height); backgroundstage.setviewport(width, height, true); foregroundstage.setviewport(maingame.width, maingame.height, true); foregroundstage.getcamera().position.set(-foregroundstage.getgutterwidth(),-foregroundstage.getgutterheight(),0); }
in tutorials have read, have seen 1 stage being used each screen. so, how fulfill both requirements in single stage? expensive have separate stages? (i have read spritebatch objects heavy!)
this how solved problem:
to rid of background stage, updated render , resize functions follows. basically, shifted bottom right corner of background (-gutterwidth,-gutterheight) , added twice values of gutter width , height region width , height of texture region. stage gone :-)
public void render(float delta) { gdx.gl.glclearcolor(0, 1, 0, 0.5f); gdx.gl.glclear(gl10.gl_color_buffer_bit | gl10.gl_depth_buffer_bit); foregroundstage.getspritebatch().begin(); foregroundstage.getspritebatch().draw(backgroundimage,-gw,-gh,backgroundimage.getregionwidth()+2*gw,backgroundimage.getregionheight()+2*gh); foregroundstage.getspritebatch().end(); foregroundstage.act(delta); foregroundstage.draw(); public void resize(int width, int height) { screenw = width; screenh = height; foregroundstage.setviewport(maingame.width, maingame.height, true); gw = foregroundstage.getgutterwidth(); gh = foregroundstage.getgutterheight(); foregroundstage.getcamera().translate(-gw,-gh,0); }
you use 2 stages, case better solve problem creating 2 groups inside single stage:
stage stage = new stage(); group background = new group(); background.setbounds(0, 0, gdx.graphics.getwidth(), gdx.graphics.getheight()); group foreground = new group(); foreground.setbounds(0, 0, gdx.graphics.getwidth(), gdx.graphics.getheight()); // notice order stage.addactor(background); stage.addactor(foreground); foreground.addactor(new actor()); // or else want add stage. background.addactor(new image()); // background image here. gdx.input.setinputprocessor(stage);
Comments
Post a Comment