开发者

ENTER_FRAME event over ENTER_FRAME event

Lets say we have a movieclip "Enemy" in the Flash library and a class "Enemy.as" is associated with it which listens to ENTER_FRAME event as follows,

public function Enemy():void
{
    //constructor of this "Enemy.as" class
    addEventListener(Event.ENTER_FRAME, move);
}

private function move(evt:Even开发者_如何转开发t):void
{
    x += 5;
}

Now my question is if this "Enemy.as" is instantiated in other class say "Main.as" which again uses ENTER_FRAME event on the same instantiated Enemy object as follows,

public function Main():void
{
    //constructor of this "Main.as" class
    enemy1 = new Enemy();
    enemy1.addEventListener(Event.ENTER_FRAME, checkCollision);
}

private function checkCollision(evt:Event):void
{
    if(enemy1.x == mainObj.x)
    {
        //do something
    }        
}

Is this the good approach in terms of optimization? Or should not use this approach at all?


From a performance point of view, it's always best to only listen for ENTER_FRAME in a single location (e.g. in your main application class) and to then invoke custom update() methods on all the objects that need to be updated. That's a very common approach for games for instance.

One reason why this is greatly superior from a performance point of view is that no new instances of Event need to be created. If you have 100 listeners (which is not uncommon when using the approach you outline) that means 100 new instances of the Event class every frame, and instantiating classes is among the heaviest things that you can do in Flash.

You rarely actually need the Event object in ENTER_FRAME handlers, so using the update() approach instead makes a lot of sense. If you can, try centralizing other events as well in performance critical applications like games.


As Richard says, it is much more efficient to use a single update (Game Loop) method when creating games. Not only from the performance point of view, but also because you get a lot more control using a single update. Like this:

public function update(deltaTime : Number) : void
{
    var gameObject : IGameObject;

    for(var i : int = 0 ; i < _gameObjects.length ; i++)
    {
        gameObject = _gameObjects[i];
        gameObject.update(deltaTime);
    }

    ...

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜