本教學以一個「遙控坦克」為例,示範 ActionScript 2.0 核心語法:鍵盤事件、三角函數移動、加速度模擬、邊界循環、元件巢狀結構。適合 AS 入門者理解「程式邏輯如何驅動視覺表現」。


onClipEvent (keyDown) {
if (Key.getCode() == 90) { // Z 鍵
_rotation -= 6; // 逆時針 6°
}
if (Key.getCode() == 88) { // X 鍵
_rotation += 6; // 順時針 6°
}
}
Key.getCode() 回傳最後按下鍵的 ASCII 碼(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(); // speed 為負值時自然後退
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;
}
true,適合移動控制;區別於 keyDown 事件(單次觸發)。