萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 軟體知識 >  >> 影像處理 >> Flash 教學

Flash 遊戲開發實作:可旋轉砲台的坦克

學習 Flash 不懂 ActionScript 會受限。其實 AS 一點也不難,這篇教學帶你打造一台可隨意開動、砲台可獨立旋轉的坦克,過程中學會基本語句、屬性、物件與方法。

環境建置

新建檔案:600×450 px、黑背景、40 fps。

一、砲台旋轉

  1. Ctrl+F8 新增影片剪輯「砲台」,繪製砲台圖形,砲台圓蓋中心務必與元件中心點 (╬) 重疊,以利旋轉。
  2. 新增影片剪輯「坦克」,「圖層 1」畫坦克主體,「圖層 2」拖入「砲台」元件。
  3. 選取「砲台」元件,F9 開啟動作面板輸入:
onClipEvent (keyDown) {
    if (Key.getCode() == 90) { // Z 鍵
        _rotation -= 6;
    }
    if (Key.getCode() == 88) { // X 鍵
        _rotation += 6;
    }
}

測試:按 Z/X 鍵砲台即可左右旋轉。Key.getCode() 取得鍵碼,字母 A-Z 對應 65-90。

二、坦克移動與轉向

回主場景,拖入「坦克」元件,加入以下程式碼:

onClipEvent (enterFrame) {
    function move() {
        _y -= Math.cos(Math.PI/180 * this._rotation) * speed;
        _x += Math.sin(Math.PI/180 * this._rotation) * speed;
    }

    if (Key.isDown(Key.UP))   move();
    if (Key.isDown(Key.DOWN)) move();

    if (Key.isDown(Key.LEFT))  _rotation -= 3;
    if (Key.isDown(Key.RIGHT)) _rotation += 3;

    // 加減速邏輯
    if (Key.isDown(Key.UP) && !Key.isDown(Key.DOWN) && speed > -3 && speed < 3) speed += 0.1;
    if (Key.isDown(Key.DOWN) && !Key.isDown(Key.UP) && speed > -3 && speed < 3) speed -= 0.1;
    if (speed > 0.1 && !Key.isDown(Key.UP) && !Key.isDown(Key.DOWN)) { move(); speed -= 0.05; }
    if (speed < -0.1 && !Key.isDown(Key.UP) && !Key.isDown(Key.DOWN)) { move(); speed += 0.05; }
    if (Key.isDown(Key.UP) && Key.isDown(Key.DOWN)) { speed /= 1.1; if (speed > -0.1 && speed < 0.1) speed = 0; }

    // 邊界循環
    if (_x <= 0) _x = 600; else if (_x >= 600) _x = 0;
    if (_y <= 0) _y = 450; else if (_y >= 450) _y = 0;
}

程式碼解析

  • move() 封裝移動邏輯,利用三角函數依旋轉角度計算 X/Y 位移。
  • Flash 座標系 Y 軸向下為正,故 _y -= ...。
  • Key.isDown() 偵測按鍵持續按下,適合方向鍵控制。
  • 速度變數 speed 實現加速、減速、慣性滑行效果。
  • 邊界判斷讓坦克穿牆循環,增加遊戲趣味。

測試影片,體驗像遙控車般靈活的坦克操控!

copyright © 萬盛學電腦網 all rights reserved