Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 遊戲 >> Android 遊戲開發

Android遊戲引擎libgdx使用教學10:雙舞台

編輯: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);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved