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

Android 遊戲開發 4:讓角色在螢幕上走動,順手搭出遊戲主迴圈骨架

編輯:Android 遊戲開發

上一節剖析的 SurfaceView,其實已經是一個堪用的遊戲框架雛形了——先不急著下結論,看完這節的 Demo 你會更有感。這個例子示範了圖片的裁切繪製、按鍵控制,以及最基礎的遊戲主迴圈結構。

public class MySurfaceView extends SurfaceView implements Callback, Runnable {

    private Thread th = new Thread(this);
    private SurfaceHolder sfh;
    private int SH, SW;                 // 螢幕高與寬
    private Canvas canvas;
    private Paint p, p2;
    private Resources res;
    private Bitmap bmp;
    private int bmp_x = 100, bmp_y = 100;

    private boolean UP, DOWN, LEFT, RIGHT;

    // 一張 13 格的角色精靈圖,每 3 格是一組行走動畫
    private int animation_up[]    = { 3, 4, 5 };
    private int animation_down[]  = { 0, 1, 2 };
    private int animation_left[]  = { 6, 7, 8 };
    private int animation_right[] = { 9, 10, 11 };
    private int animation_init[]  = animation_down;
    private int frame_count;

    public MySurfaceView(Context context) {
        super(context);
        this.setKeepScreenOn(true);
        res = this.getResources();
        bmp = BitmapFactory.decodeResource(res, R.drawable.enemy1);
        sfh = this.getHolder();
        sfh.addCallback(this);
        p = new Paint();
        p.setColor(Color.YELLOW);
        p2 = new Paint();
        p2.setColor(Color.RED);
        p.setAntiAlias(true);
        setFocusable(true);            // 註解 1
    }

    public void surfaceCreated(SurfaceHolder holder) {
        SH = this.getHeight();
        SW = this.getWidth();
        th.start();                    // 主迴圈啟動
    }

    public void draw() {
        canvas = sfh.lockCanvas();
        canvas.drawRect(0, 0, SW, SH, p);          // 註解 2:整螢幕清底
        canvas.save();                             // 註解 3:保存畫布狀態
        canvas.drawText("Himi", bmp_x - 2, bmp_y - 10, p2);
        // 只保留角色所在的那一小格,避免整張精靈圖被畫出來
        canvas.clipRect(bmp_x, bmp_y,
                bmp_x + bmp.getWidth() / 13, bmp_y + bmp.getHeight());

        if (animation_init == animation_up) {
            canvas.drawBitmap(bmp,
                    bmp_x - animation_up[frame_count] * (bmp.getWidth() / 13), bmp_y, p);
        } else if (animation_init == animation_down) {
            canvas.drawBitmap(bmp,
                    bmp_x - animation_down[frame_count] * (bmp.getWidth() / 13), bmp_y, p);
        } else if (animation_init == animation_left) {
            canvas.drawBitmap(bmp,
                    bmp_x - animation_left[frame_count] * (bmp.getWidth() / 13), bmp_y, p);
        } else if (animation_init == animation_right) {
            canvas.drawBitmap(bmp,
                    bmp_x - animation_right[frame_count] * (bmp.getWidth() / 13), bmp_y, p);
        }
        canvas.restore();                          // 註解 3:還原畫布狀態
        sfh.unlockCanvasAndPost(canvas);
    }

    public void cycle() {                          // 更新角色座標與動畫影格
        if (DOWN) {
            bmp_y += 5;
        } else if (UP) {
            bmp_y -= 5;
        } else if (LEFT) {
            bmp_x -= 5;
        } else if (RIGHT) {
            bmp_x += 5;
        }

        if (DOWN || UP || LEFT || RIGHT) {
            if (frame_count < 2) {
                frame_count++;
            } else {
                frame_count = 0;
            }
        }
        if (DOWN == false && UP == false && LEFT == false && RIGHT == false) {
            frame_count = 0;                       // 放開方向鍵回到第一格
        }
    }

    @Override
    public boolean onKeyDown(int key, KeyEvent event) {
        if (key == KeyEvent.KEYCODE_DPAD_UP) {
            if (UP == false) {
                animation_init = animation_up;
            }
            UP = true;
        } else if (key == KeyEvent.KEYCODE_DPAD_DOWN) {
            if (DOWN == false) {
                animation_init = animation_down;
            }
            DOWN = true;
        } else if (key == KeyEvent.KEYCODE_DPAD_LEFT) {
            if (LEFT == false) {
                animation_init = animation_left;
            }
            LEFT = true;
        } else if (key == KeyEvent.KEYCODE_DPAD_RIGHT) {
            if (RIGHT == false) {
                animation_init = animation_right;
            }
            RIGHT = true;
        }
        return super.onKeyDown(key, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (DOWN) {
            DOWN = false;
        } else if (UP) {
            UP = false;
        } else if (LEFT) {
            LEFT = false;
        } else if (RIGHT) {
            RIGHT = false;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void run() {
        while (true) {
            draw();        // 畫
            cycle();       // 更新
            try {
                Thread.sleep(100);
            } catch (Exception ex) { }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { }
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) { }
}

遊戲主迴圈的骨架

整份程式碼最重要的結構其實只有 run() 裡那三行:畫 → 更新 → 睡一會兒。這是所有遊戲引擎心臟的通用樣貌。draw 負責把目前的狀態呈現在螢幕上,cycle 負責改寫狀態(座標、影格、計分…),Thread.sleep() 則控制幀率與 CPU 占用。這個 sleep 的數值直接決定了遊戲節奏,實作時通常會再拿計時器去動態補償,讓不同效能的機型跑出一致的結果。

註解 1:按鍵為什麼沒反應

setFocusable(true) 是回應實體按鍵的關鍵。自訂一個繼承自 View 的類別並重寫 onKeyDown() 之後,只有當這個 View 取得焦點時,方法才會被呼叫;而 Activity 的 onKeyDown() 只有在所有子元件都沒有處理該按鍵時才會被觸發。少了這一行,事件就在別處被吃掉了。

這裡還有個設計上的小細節:onKeyDown 只負責「切換動畫組」與「設定方向旗標」,onKeyUp 負責「清除旗標」,真正的位移則留給 cycle() 每一幀統一處理。把「輸入」與「狀態更新」分開,是避免邏輯糾纏的基本手法。

註解 2:清屏

用 drawRect() 填滿整個畫布來清屏只是一種做法,drawRGB() 或 fillRect() 都能達到同樣效果。

順帶比較一個常被搞混的差異:繼承 View 時,onDraw() 是由系統決定期他指出現的,我們只能透過 invalidate() 或 postInvalidate() 請求系統重繪;而在 SurfaceView 中,繪製時機完全由我們自己在執行緒裡掌控。這正是遊戲幾乎都選 SurfaceView 的原因——畫面更新節奏必須握在自己手上。

註解 3:canvas.save() 與 canvas.restore()

這兩個方法總是成對出現,作用是「保存畫布狀態」與「還原到保存時的狀態」。

為什麼需要它?當你呼叫 scale()、rotate()、translate() 這類方法時,它作用的是整個畫布,而不是單一物件。一旦呼叫之後沒有還原,後續畫上去的所有東西都會跟著被變形或位移。因此在做局部變換之前先 save(),做完之後 restore(),就能把變換的影響範圍鎖在這段程式碼之內。

用兩段對照的程式碼就很清楚。假設有 bmp1 與 bmp2 兩張圖:

// 有 save / restore:bmp2 不受縮放影響
public void draw() {
    Canvas canvas = sfh.lockCanvas();
    canvas.drawColor(Color.BLACK);
    canvas.drawBitmap(bmp1, 0, 0, paint);
    canvas.save();
    canvas.scale(1.5f, 1.5f);
    canvas.restore();
    canvas.drawBitmap(bmp2, 0, 0, paint);
    sfh.unlockCanvasAndPost(canvas);
}
// 沒有 save / restore:bmp2 同樣被放大 1.5 倍
public void draw() {
    Canvas canvas = sfh.lockCanvas();
    canvas.drawColor(Color.BLACK);
    canvas.drawBitmap(bmp1, 0, 0, paint);
    canvas.scale(1.5f, 1.5f);
    canvas.drawBitmap(bmp2, 0, 0, paint);
    sfh.unlockCanvasAndPost(canvas);
}

而如果你就是想要只讓 bmp2 被縮放,正確的寫法是把變換夾在中間:

public void draw() {
    Canvas canvas = sfh.lockCanvas();
    canvas.drawColor(Color.BLACK);
    canvas.drawBitmap(bmp1, 0, 0, paint);
    canvas.save();
    canvas.scale(1.5f, 1.5f);
    canvas.drawBitmap(bmp2, 0, 0, paint);
    canvas.restore();
    sfh.unlockCanvasAndPost(canvas);
}

回到本節的角色行走:clipRect() 決定「畫布上哪些區域可以被繪製」,再搭配把整張精靈圖往反方向平移,讓指定影格正好落在裁切框內——這就是最經典的精靈圖動畫原理。而 save() / restore() 確保這個裁切與位移不會污染到之後的文字繪製。把這套結構記熟,往後加上碰撞偵測、地圖捲動、敵人 AI,都只是在同一個迴圈裡繼續擴充而已。

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