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

Android遊戲引擎libgdx使用教學13:在TiledMap地圖中加入角色與移動控制

編輯:Android 遊戲開發

本文承接上一篇(libgdx使用教學12:如何使用TiledMap地圖)。地圖建好之後,接下來就是讓主角登場。由於前面已經介紹過 TiledMap 與 Stage 的結合方式,角色處理其實相當單純。

你可以繼承 Actor 類別自訂一個主角類,這裡為了示範方便,我偷個懶直接用 Image 來代替。首先編輯 TMX 檔,新增一個物件層(Object Layer)。

接著在主角要出現的位置放一個形狀,並取名為 play1。

我們的主角素材如下:

讓主角出現

思路很簡單:遍歷 map 中的所有 Object,如果名稱與 play1 相符,就建立一個 Image 實例,位置與該 Object 一致,再加入舞台。關鍵程式碼如下:

for (TiledObjectGroup group : map.objectGroups) {
    for (TiledObject object : group.objects) {
        if ("play1".equals(object.name)) {
            player = new Image(new TextureRegion(new Texture(Gdx.files
                .internal("map/player.png")), 0, 0, 27, 40));
            player.x = object.x;
            player.y = tileMapRenderer.getMapHeightUnits() - object.y; // map是左上角,Stage是左下角
            stage.addActor(player);
        }
    }
}

效果如下:

讓主角動起來

首先是操作方式。Android 設備優先選用觸控:按住前方不放,主角向前;按住上方不放,主角向上。那麼要如何判斷我們按住的是哪個方向呢?

如圖所示,黃色的是 Stage,粉紅色邊框是整個 Map(有部分顯示、有部分未顯示),右下角的綠點是主角位置,我們假設紅點是觸碰點。

把紅點判定為「向前」。這裡提供一種做法,方法並不唯一,我的判定方式也不一定最符合使用者體驗。做法是:以主角位置為原點重建座標系,取得觸碰點的新座標 x、y。

判斷觸碰點落在新座標系的哪個象限,再比較 x、y 的大小,就能決定方向了。

Vector3 tmp = new Vector3(x, y, 0);
stage.getCamera().unproject(tmp);
float newx = tmp.x - player.x;
float newy = tmp.y - player.y;
if (newx > 0 && newy > 0) {
    if (newx > newy) { ChangeDirect(4); } else { ChangeDirect(1); }
} else if (newx > 0 && newy < 0) {
    if (newx > -newy) { ChangeDirect(4); } else { ChangeDirect(2); }
} else if (newx < 0 && newy > 0) {
    if (-newx > newy) { ChangeDirect(3); } else { ChangeDirect(1); }
} else {
    if (-newx > -newy) { ChangeDirect(3); } else { ChangeDirect(2); }
}

直接移動 Camera 位置可以讓地圖移動,但主角卻會從畫面消失。處理辦法是:讓你希望持續顯示在地圖上的 Actor 座標跟著 Camera 一起移動。

private void CameraMove(Vector3 vector3) {
    stage.getCamera().position.add(vector3);
    for (Actor actor : stage.getActors()) {
        actor.x += vector3.x;
        actor.y += vector3.y;
    }
}

完整程式碼

package com.cnblogs.htynkn.game;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g2d.tiled.TileAtlas;
import com.badlogic.gdx.graphics.g2d.tiled.TileMapRenderer;
import com.badlogic.gdx.graphics.g2d.tiled.TiledLoader;
import com.badlogic.gdx.graphics.g2d.tiled.TiledMap;
import com.badlogic.gdx.graphics.g2d.tiled.TiledObject;
import com.badlogic.gdx.graphics.g2d.tiled.TiledObjectGroup;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;

public class firstGame implements ApplicationListener, InputProcessor {

    Stage stage;
    float width;
    float height;
    private TiledMap map;
    private TileAtlas atlas;
    private TileMapRenderer tileMapRenderer;
    Image player;
    Vector3 camDirection = new Vector3(1, 1, 0);
    Vector2 maxCamPosition = new Vector2(0, 0);
    Vector3 moveVector = new Vector3(0, 0, 0);
    boolean isPress;

    @Override
    public void create() {
        final String path = "map/";
        final String mapname = "tilemap";
        FileHandle mapHandle = Gdx.files.internal(path + mapname + ".tmx");
        map = TiledLoader.createMap(mapHandle);
        atlas = new TileAtlas(map, Gdx.files.internal("map/"));
        tileMapRenderer = new TileMapRenderer(map, atlas, 10, 10);
        maxCamPosition.set(tileMapRenderer.getMapWidthUnits(),
            tileMapRenderer.getMapHeightUnits());

        width = Gdx.graphics.getWidth();
        height = Gdx.graphics.getHeight();
        stage = new Stage(width, height, true);
        Label label = new Label("FPS:", new LabelStyle(new BitmapFont(Gdx.files
            .internal("font/blue.fnt"),
            Gdx.files.internal("font/blue.png"), false), Color.WHITE),
            "fpsLabel");
        label.y = height - label.getPrefHeight();
        label.x = 0;
        stage.addActor(label);

        for (TiledObjectGroup group : map.objectGroups) {
            for (TiledObject object : group.objects) {
                if ("play1".equals(object.name)) {
                    player = new Image(new TextureRegion(new Texture(Gdx.files
                        .internal("map/player.png")), 0, 0, 27, 40));
                    player.x = object.x;
                    player.y = tileMapRenderer.getMapHeightUnits() - object.y; // map是左上角,Stage是左下角
                    stage.addActor(player);
                }
            }
        }

        InputMultiplexer inputMultiplexer = new InputMultiplexer();
        inputMultiplexer.addProcessor(this);
        inputMultiplexer.addProcessor(stage);
        Gdx.input.setInputProcessor(inputMultiplexer);
    }

    @Override
    public void render() {
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        OrthographicCamera c = (OrthographicCamera) stage.getCamera();
        if (isPress) {
            CameraMove(moveVector);
        }
        ((Label) stage.findActor("fpsLabel")).setText("FPS: "
            + Gdx.graphics.getFramesPerSecond());
        stage.act(Gdx.graphics.getDeltaTime());
        tileMapRenderer.render(c);
        stage.draw();
    }

    private void CameraMove(Vector3 vector3) {
        stage.getCamera().position.add(vector3);
        for (Actor actor : stage.getActors()) {
            actor.x += vector3.x;
            actor.y += vector3.y;
        }
    }

    private void ChangeDirect(int typeId) {
        switch (typeId) {
        case 1:
            moveVector.set(0, 1, 0);
            Gdx.app.log("方向變動", "向上");
            break;
        case 2:
            moveVector.set(0, -1, 0);
            Gdx.app.log("方向變動", "向下");
            break;
        case 3:
            moveVector.set(-1, 0, 0);
            Gdx.app.log("方向變動", "向左");
            break;
        case 4:
            moveVector.set(1, 0, 0);
            Gdx.app.log("方向變動", "向右");
            break;
        }
    }

    @Override
    public boolean touchDown(int x, int y, int pointer, int button) {
        Vector3 tmp = new Vector3(x, y, 0);
        stage.getCamera().unproject(tmp);
        float newx = tmp.x - player.x;
        float newy = tmp.y - player.y;
        if (newx > 0 && newy > 0) {
            if (newx > newy) { ChangeDirect(4); } else { ChangeDirect(1); }
        } else if (newx > 0 && newy < 0) {
            if (newx > -newy) { ChangeDirect(4); } else { ChangeDirect(2); }
        } else if (newx < 0 && newy > 0) {
            if (-newx > newy) { ChangeDirect(3); } else { ChangeDirect(1); }
        } else {
            if (-newx > -newy) { ChangeDirect(3); } else { ChangeDirect(2); }
        }
        isPress = true;
        return false;
    }

    @Override
    public boolean touchUp(int x, int y, int pointer, int button) {
        isPress = false;
        return false;
    }

    // 其餘 ApplicationListener / InputProcessor 方法略
}

我不知道怎麼錄製手機畫面,所以只能用模擬器示範,但真機運行相當流暢,完全沒問題。

若有多個角色,做法完全一樣,多建幾個 Object 即可。目前可以明顯看出我們的忍者行走地圖毫無障礙;如果一直往前走,會發現地圖有一部分消失,這些問題會在後續文章慢慢解決。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved