學習 Flash 不懂 ActionScript 會受限。其實 AS 一點也不難,這篇教學帶你打造一台可隨意開動、砲台可獨立旋轉的坦克,過程中學會基本語句、屬性、物件與方法。
新建檔案:600×450 px、黑背景、40 fps。
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 位移。_y -= ...。Key.isDown() 偵測按鍵持續按下,適合方向鍵控制。speed 實現加速、減速、慣性滑行效果。測試影片,體驗像遙控車般靈活的坦克操控!