android游戏开发框架libgdx的使用(十)—双舞台
转载声明:http://www.cnblogs.com/htynkn/archive/2012/01/09/libgdx_10.html
游戏屏幕最常见的就是一个变化较少的背景加上一系列和用户交互的角色和部件。为了方便管理你还可以为背景建个Group方便管理。
但是有时候写的时候没有想到这个问题,或者是背景不是单纯的一个图片什么的,背景和角色还有一些混合逻辑分布在两个Stage里。
我重写太麻烦,想想反正都是SpritBatch绘制出来的,用双舞台大不了多个摄像头。马上试试还真行。
先看看Stage的draw方法:
1 /** Renders the stage */ 2 public void draw () { 3 camera.update(); 4 if (!root.visible) return; 5 batch.setProjectionMatrix(camera.combined); 6 batch.begin(); 7 root.draw(batch, 1); 8 batch.end(); 9 }
batch的话两个舞台可以共用。用Stage(width, height, stretch, batch)实例化第二个舞台。
代码如下:
1 package com.cnblogs.htynkn.game; 2 3 import com.badlogic.gdx.ApplicationListener; 4 import com.badlogic.gdx.Gdx; 5 import com.badlogic.gdx.InputProcessor; 6 import com.badlogic.gdx.graphics.GL10; 7 import com.badlogic.gdx.graphics.Texture; 8 import com.badlogic.gdx.graphics.g2d.TextureRegion; 9 import com.badlogic.gdx.scenes.scene2d.Stage; 10 import com.badlogic.gdx.scenes.scene2d.ui.Image; 11 12 public class JavaGame implements ApplicationListener { 13 14 Stage stage1; 15 Stage stage2; 16 float width; 17 float height; 18 19 @Override 20 public void create() { 21 width = Gdx.graphics.getWidth(); 22 height = Gdx.graphics.getHeight(); 23 stage1 = new Stage(width, height, true); 24 stage2 = new Stage(width, height, true,stage1.getSpriteBatch()); 25 Image image = new Image(new TextureRegion(new Texture(Gdx.files 26 .internal("img/sky.jpg")), 50, 50, 480, 320)); 27 stage1.addActor(image); 28 Image image2 = new Image(new TextureRegion(new Texture(Gdx.files 29 .internal("img/baihu.png")), 217, 157)); 30 image2.x=(width-image2.width)/2; 31 image2.y=(height-image2.height)/2; 32 stage2.addActor(image2); 33 } 34 35 @Override 36 public void dispose() { 37 // TODO Auto-generated method stub 38 39 } 40 41 @Override 42 public void pause() { 43 // TODO Auto-generated method stub 44 45 } 46 47 @Override 48 public void render() { 49 Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); 50 stage1.act(Gdx.graphics.getDeltaTime()); 51 stage2.act(Gdx.graphics.getDeltaTime()); 52 stage1.draw(); 53 stage2.draw(); 54 } 55 56 @Override 57 public void resize(int width, int height) { 58 // TODO Auto-generated method stub 59 60 } 61 62 @Override 63 public void resume() { 64 // TODO Auto-generated method stub 65 66 } 67 }
效果:
如果你对于效率追求比较极致,可以考虑对于SpritBatch的缓冲数进行修改。
还有一个需要注意,背景舞台应该先绘制,其他部件后绘制,不然效果就是下图:
关于舞台的输入控制,不能简单的使用:
1 Gdx.input.setInputProcessor(stage1); 2 Gdx.input.setInputProcessor(stage2);
应该这样做:
1 InputMultiplexer inputMultiplexer=new InputMultiplexer(); 2 inputMultiplexer.addProcessor(stage1); 3 inputMultiplexer.addProcessor(stage2);



浙公网安备 33010602011771号