演示文件源码下载:http://kerryas.googlecode.com/files/swfs_communication.rar
假设有一个主 SWf 名为 main.swf 加载一个名为 game.swf 的游戏模块:
1. main 里面使用 Loader 将 game.swf 加载进来;
2. 在 game 中定义 public function moveBall(speed:Number)
方法,用于开始游戏;
3. 在 main 里面使用类似 loader["content"].moveBall(speed) 的语句调用 game.swf
里面的方法;
4. game.swf 与 main.swf 通信的方法,可以使用 dispatchEvent 方法与 main.swf
通信,也可以继续使用上述方法。
下面请看示例:
1. 首先创建被调用的 game.swf:
package {
import
flash.display.Sprite;
import
flash.events.Event;
import
flash.system.Security;
public class
Game extends Sprite {
private var
ball:Sprite;
private var
speed:Number;
public
function Game() {
// 在 Flash
IDE 中执行 Debug
Security.allowInsecureDomain("*");
if (stage)
init();
else
addEventListener(Event.ADDED_TO_STAGE, init);
}
private
function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
ball = new
Sprite();
ball.graphics.beginFill(0xFF0000);
ball.graphics.drawCircle(0, 0, 50);
ball.graphics.endFill();
addChild(ball);
ball.x =
50;
ball.y =
stage.stageHeight / 2;
}
public
function moveBall(speed:Number):void {
this.speed =
speed;
addEventListener(Event.ENTER_FRAME, onGameLoop);
}
private
function onGameLoop(e:Event):void {
ball.x +=
speed;
}