編輯:Android 遊戲開發
遊戲畫面最常見的結構,就是一個變化較少的背景,加上一系列與使用者互動的角色和元件。為了方便管理,你甚至可以為背景建立一個 Group。但有時候在開發一開始沒想到這個問題,或者背景並不是單純的一張圖片,導致背景與角色之間存在一些混合邏輯,分散在兩個 Stage 裡。重寫太麻煩,我心想反正都是靠 SpriteBatch 繪製出來的,用雙舞台大不了多一個攝影機而已,於是馬上試了試,還真的可行。
先看看 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,兩個舞台可以共用。用 Stage(width, height, stretch, batch) 建立第二個舞台即可。
package com.cnblogs.htynkn.game;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
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 render() {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
stage1.act(Gdx.graphics.getDeltaTime());
stage2.act(Gdx.graphics.getDeltaTime());
stage1.draw();
stage2.draw();
}
// 其餘生命週期方法略
}
效果:

如果你對效能有比較極致的追求,可以考慮調整 SpriteBatch 的緩衝數量。另外要注意:背景舞台應該先繪製,其他元件後繪製,否則效果就會像下圖那樣:

關於舞台的輸入控制,不能簡單地這樣寫:
Gdx.input.setInputProcessor(stage1);
Gdx.input.setInputProcessor(stage2);
應該改用 InputMultiplexer:
InputMultiplexer inputMultiplexer = new InputMultiplexer();
inputMultiplexer.addProcessor(stage1);
inputMultiplexer.addProcessor(stage2);
Gdx.input.setInputProcessor(inputMultiplexer);
Android 遊戲開發 5:以登入畫面為例,實作 Activity 切換與資料傳遞
這一節用一個登入畫面的小 Demo,把「多個 Activity 之間如何切換、如何傳遞資料」講清楚。示範著重在功能,所以版面沒有特別美化;你完全可以自己在 XML 或程式
Android遊戲引擎libgdx使用教學11:如何使用Skin與UI設定檔
libgdx 的 UI 改進幅度很大,過去各種稀奇古怪的問題大多已被解決,UI 類型也大致齊全,建議大家下載最新版本來使用。 我認為 UI 唯一較複雜的地方在於各種樣式的
Android遊戲引擎libgdx使用教學2:如何繪製圖形
本文主要為大家講解使用 libgdx 時圖形的繪製,詳細介紹了圖形繪製的方法與步驟,大家可以細細研讀。 首先了解何謂 texture。按照英文解釋來理解:一張圖片從原始格
Android遊戲開發實戰(十四):繪製觸摸軌跡曲線
上一章我們已經掌握了如何處理遊戲中的觸摸事件,這一章再往前邁一步——把手指滑過屏幕的軌跡,變成一條流暢的曲線畫出來。在 onTouchEvent 方法裡,我們能實時拿到手