Android游戲引擎libgdx使用教程10:雙舞臺(tái)
游戲屏幕最常見(jiàn)的就是一個(gè)變化較少的背景加上一系列和用戶(hù)交互的角色和部件。為了方便管理你還可以為背景建個(gè)Group方便管理。
但是有時(shí)候?qū)懙臅r(shí)候沒(méi)有想到這個(gè)問(wèn)題,或者是背景不是單純的一個(gè)圖片什么的,背景和角色還有一些混合邏輯分布在兩個(gè)Stage里。我重寫(xiě)太麻煩,想想反正都是SpritBatch繪制出來(lái)的,用雙舞臺(tái)大不了多個(gè)攝像頭。馬上試試還真行。
先看看Stage的draw方法:
- /** Renders the stage */
- public void draw () {
- camera.update();
- if (!root.visible) return;
- batch.setProjectionMatrix(camera.combined);
- batch.begin();
- root.draw(batch, 1);
- batch.end();
- }
batch的話兩個(gè)舞臺(tái)可以共用。用Stage(width, height, stretch, batch)實(shí)例化第二個(gè)舞臺(tái)。
代碼如下:
- package com.cnblogs.htynkn.game;
- import com.badlogic.gdx.ApplicationListener;
- import com.badlogic.gdx.Gdx;
- import com.badlogic.gdx.InputProcessor;
- import com.badlogic.gdx.graphics.GL10;
- import com.badlogic.gdx.graphics.Texture;
- import com.badlogic.gdx.graphics.g2d.TextureRegion;
- import com.badlogic.gdx.scenes.scene2d.Stage;
- import com.badlogic.gdx.scenes.scene2d.ui.Image;
- public class JavaGame implements ApplicationListener {
- Stage stage1;
- Stage stage2;
- float width;
- float height;
- @Override
- public void create() {
- width = Gdx.graphics.getWidth();
- height = Gdx.graphics.getHeight();
- stage1 = new Stage(width, height, true);
- stage2 = new Stage(width, height, true,stage1.getSpriteBatch());
- Image image = new Image(new TextureRegion(new Texture(Gdx.files
- .internal("img/sky.jpg")), 50, 50, 480, 320));
- stage1.addActor(image);
- Image image2 = new Image(new TextureRegion(new Texture(Gdx.files
- .internal("img/baihu.png")), 217, 157));
- image2.x=(width-image2.width)/2;
- image2.y=(height-image2.height)/2;
- stage2.addActor(image2);
- }
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
- }
- @Override
- public void pause() {
- // TODO Auto-generated method stub
- }
- @Override
- public void render() {
- Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
- stage1.act(Gdx.graphics.getDeltaTime());
- stage2.act(Gdx.graphics.getDeltaTime());
- stage1.draw();
- stage2.draw();
- }
- @Override
- public void resize(int width, int height) {
- // TODO Auto-generated method stub
- }
- @Override
- public void resume() {
- // TODO Auto-generated method stub
- }
- }
效果:
如果你對(duì)于效率追求比較極致,可以考慮對(duì)于SpritBatch的緩沖數(shù)進(jìn)行修改。
還有一個(gè)需要注意,背景舞臺(tái)應(yīng)該先繪制,其他部件后繪制,不然效果就是下圖:
關(guān)于舞臺(tái)的輸入控制,不能簡(jiǎn)單的使用:
- Gdx.input.setInputProcessor(stage1);
- Gdx.input.setInputProcessor(stage2);
應(yīng)該這樣做:
- InputMultiplexer inputMultiplexer=new InputMultiplexer();
- inputMultiplexer.addProcessor(stage1);
- inputMultiplexer.addProcessor(stage2);