在实际开发中我们需要在不同的时候切换不同游戏场景,比如需要有游戏设置界面、有些菜单界面和游戏主界面。
Screen 游戏场景
在Libgdx中Screen代表了一个游戏场景,有点类似coco2d-x中的Scene,但是Screen不能独立存在,必须依靠Game来切换。
官方的注释: Screen代表了应用程序中众多的场景之一(Screens),例如:主菜单,设置菜单,游戏场景等。Screen不会自动调用#dispose()方法
/** Called when this screen becomes the current screen for a {@link Game}. 每次切换到此Screen都会调用*/
public void show ();
/** Called when the screen should render itself.
* @param delta The time in seconds since the last render. */
public void render (float delta);
/** @see ApplicationListener#resize(int, int) */
public void resize (int width, int height);
/** @see ApplicationListener#pause() */
public void pause ();
/** @see ApplicationListener#resume() */
public void resume ();
/** Called when this screen is no longer the current screen for a {@link Game}. */
public void hide ();
/** Called when this screen should release all resources. */
public void dispose ();
Game implements ApplicationListener
Game继承自ApplicationListener,同时也有游戏生存的生命周期。
protected Screen screen;
@Override
public void dispose () {
if (screen != null) screen.hide();
}
@Override
public void pause () {
if (screen != null) screen.pause();
}
@Override
public void resume () {
if (screen != null) screen.resume();
}
@Override
public void render () {
if (screen != null) screen.render(Gdx.graphics.getDeltaTime());
}
@Override
public void resize (int width, int height) {
if (screen != null) screen.resize(width, height);
}
/** Sets the current screen. {@link Screen#hide()} is called on any old screen, and {@link Screen#show()} is called on the new
* screen, if any.
* @param screen may be {@code null} */
public void setScreen (Screen screen) {
if (this.screen != null) this.screen.hide();
this.screen = screen;
if (this.screen != null) {
this.screen.show();
this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
}
/** @return the currently active {@link Screen}. */
public Screen getScreen () {
return screen;
}
通过上面代码可以看到在游戏dispose()时,实际上是调用的screen.hide()方法,同时在setScreen(Screen screen)时也是调用的screen.hide()方法,并没有看到有调用screen.dispose()方法。因此在实际开发过程中,我们要注意自己处理好Screen的内存,防止内存泄漏。