隔离行为

来源:互联网 发布:朝鲜核试验 东北 知乎 编辑:程序博客网 时间:2024/04/30 02:19

尽可能隔离事件,例如单个处理函数中的 Event.ENTER_FRAME 事件。
通过在单个处理函数的 Apple 类中隔离 Event.ENTER_FRAME 事件,可进一步优化此代码。此技术可节省 CPU 资源。以下示例介绍了一种不同的方法,在该方法中, BitmapApple 类不再处理移动行为:
package org.bytearray.bitmap
{
import flash.display.Bitmap;
import flash.display.BitmapData;
public class BitmapApple extends Bitmap
{
private var destinationX:Number;
private var destinationY:Number;
public function BitmapApple(buffer:BitmapData)
{
super (buffer);
smoothing = true;
}
}
以下代码对苹果进行了实例化,并在单个处理函数中处理其移动行为:
import org.bytearray.bitmap.BitmapApple;
const MAX_NUM:int = 100;
var holder:Sprite = new Sprite();
addChild(holder);
var holderVector:Vector.<BitmapApple> = new Vector.<BitmapApple>(MAX_NUM, true);
var source:AppleSource = new AppleSource();
var bounds:Object = source.getBounds(source);
var mat:Matrix = new Matrix();
mat.translate(-bounds.x,-bounds.y);
stage.quality = StageQuality.BEST;
var buffer:BitmapData = new BitmapData(source.width+1,source.height+1, true,0);
buffer.draw(source,mat);
stage.quality = StageQuality.LOW;
var bitmapApple:BitmapApple;
for (var i:int = 0; i< MAX_NUM; i++)
{
bitmapApple = new BitmapApple(buffer);
bitmapApple.destinationX = Math.random()*stage.stageWidth;
bitmapApple.destinationY = Math.random()*stage.stageHeight;
holderVector[i] = bitmapApple;
holder.addChild(bitmapApple);
}
stage.addEventListener(Event.ENTER_FRAME,onFrame);
var lng:int = holderVector.length
function onFrame(e:Event):void
{
for (var i:int = 0; i < lng; i++)
{
bitmapApple = holderVector[i];
bitmapApple.alpha = Math.random();
bitmapApple.x -= (bitmapApple.x - bitmapApple.destinationX) *.5;
bitmapApple.y -= (bitmapApple.y - bitmapApple.destinationY) *.5;
if (Math.abs(bitmapApple.x - bitmapApple.destinationX ) < 1 &&
Math.abs(bitmapApple.y - bitmapApple.destinationY ) < 1)
{
bitmapApple.destinationX = Math.random()*stage.stageWidth;
bitmapApple.destinationY = Math.random()*stage.stageHeight;
}
}
}
结果是单个 Event.ENTER_FRAME 事件即可处理移动,而不是使用 200 个处理函数来移动每个苹果。可轻松地暂停整个动画,这在游戏中非常有用。
例如,一个简单游戏可以使用以下处理函数:
stage.addEventListener(Event.ENTER_FRAME, updateGame);
function updateGame (e:Event):void
{
gameEngine.update();
}
下一步是使苹果与鼠标或键盘交互,这要求修改 BitmapApple 类。
package org.bytearray.bitmap
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
public class BitmapApple extends Sprite
{
public var destinationX:Number;
public var destinationY:Number;
private var container:Sprite;
private var containerBitmap:Bitmap;
public function BitmapApple(buffer:BitmapData)
{
container = new Sprite();
containerBitmap = new Bitmap(buffer);
containerBitmap.smoothing = true;
container.addChild(containerBitmap);
addChild(container);
}
}
结果是 BitmapApple 实例与传统 Sprite 对象一样是交互式的。然而,这些实例链接到单个位图,在转换显示对象时不会重新采样。

原创粉丝点击