前回、予告したクラスが
FrameHelperというクラスである。これを用いると、ENTER_FRAMEイベントを意識することなく、そのイベントを利用できる。開発者をaddEventListener、removeEventListenerの呪縛から開放してくれる(もちろん、メモリリークのリスクがゼロになるわけではない)。「ENTER FRAME イベント その1」で紹介したコードは、次のように書き換えられる。
package {
import com.toritoriworks.helpers.FrameHelper;
import flash.display.Shape;
import flash.display.Sprite;
[SWF(width="240",height="180",frameRate="24",backgroundColor="0x336699")]
public class EnterFrame extends Sprite {
private var _shape:Shape;
public function EnterFrame() {
_shape = new Shape();
_shape.graphics.beginFill(0x339900);
_shape.graphics.drawRoundRect(0,0,10,10,5);
_shape.graphics.endFill();
_shape.y = 100;
addChild(_shape);
FrameHelper.setup(_shape,null,mainLoop,null);
}
private function mainLoop():Boolean {
_shape.x += 5;
if (_shape.x > 240) {
_shape.x = 0;
}
return true;
}
}
}
ここで、mainLoop()関数がfalseで終了するようにすると、ENTER_FRAMEのイベントリスナーは勝手に解放されるようになっている。それを利用した実装例を次に示す。矩形がズームインしてくる例である。
package {
import com.toritoriworks.helpers.FrameHelper;
import flash.display.Shape;
import flash.display.Sprite;
[SWF(width="240",height="180",frameRate="24",backgroundColor="0x336699")]
public class EnterFrame2 extends Sprite {
private var _shape:Shape;
public function EnterFrame2() {
_shape = new Shape();
_shape.graphics.beginFill(0x339900);
_shape.graphics.drawRoundRect(-40,-40,80,80,5);
_shape.graphics.endFill();
addChild(_shape);
_shape.x = 100;
_shape.y = 100;
FrameHelper.setup(_shape,begin,mainLoop,finish);
}
private function begin():void {
_shape.scaleX = .1;
_shape.scaleY = .1;
}
private function mainLoop():Boolean {
_shape.scaleX += (1-_shape.scaleX) * .1;
_shape.scaleY += (1-_shape.scaleY) * .1;
return _shape.scaleX < .98;
}
private function finish():void {
_shape.scaleX = 1;
_shape.scaleY = 1;
}
}
}
ご覧のとおり、ENTER_FRAMEのイベントの登録・開放を意識することなく実装できる。これは、開発者への負荷をかなり軽減するものと信じる。
上記二例では、単にENTER_FRAMEイベント内の処理が終わるのをただ待つだけである。しかし、「ENTER_FRAME イベント その2」のチャートで示したとおり、処理の流れを制御することもできる。次回ではその例を示したいと思う。
FrameHelperクラスのダウンロードは、
こちらから。