samedi 26 septembre 2015

AS3 - delays between addEventLisener and moving an Object

I have a project in which I call a class 3 times named Enemy like this:

public class Main extends MovieClip
{       
    //Enemy 
    private var _Enemy:Enemy;
    private var enemies:Vector.<Enemy> = new Vector.<Enemy>();

//main public

private function init(e:Event = null):void 
{
    removeEventListener(Event.ADDED_TO_STAGE, init);
    setEnemies(3);  //call 3 times          
}


private function setEnemies(numbers:Number):void
{
    for (var i:int = 0; numbers > i; i++)
    {
    _Enemy = new Enemy();       
    addChild(_Enemy);
    //_Enemy.isAlive = true;
    enemies.push(_Enemy);

    }

}

Here's the key contents of enemy:

public class Enemy extends Sprite 
{   

    private var randomX:Number = 1;
    private var randomY:Number = 1;

    public function Enemy()  
    {

        var _BlackFoe:BlackEnemy = new BlackEnemy; 
        addChild(_BlackFoe); // add the bitmap to stage
        SpawnNow();

        addEventListener(Event.ADDED_TO_STAGE, stageAddHandler);

    }

    private function stageAddHandler(e:Event):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, stageAddHandler);
        stage.addEventListener(Event.ENTER_FRAME, MoveNow);

    }



    public function MoveNow(event:Event):void
    {
            x += randomX;
            y += randomY;
            //trace(randomX, randomY);
            if (x >= 780 || x <= 20 ) // Check 2 conditions sepreatly: Enemy x is bigger than the stage's width(800) - 20 ? (x>780) | Enemy x smaller than the stage's width + 20? (x<20)
            {   
            randomX = randomX * -1;
            //trace("Changing X to: " + randomX);
            }   

            if (y >= 580 || y <= 0 ) 
            {   
             randomY = randomY * -1;
             //ce("Changing Y to: " + randomY);
            }   

    }

    public function SpawnNow():void
    {

        var Random:int = 50 + Math.floor( Math.random() * 730 ) 
        x = Random; 
        y = 30;

    }

Well it's pretty simple, 3 enemies start at random positions and bump on to borders and change directions (*-1). BlackEnemy, which is their image, is a class inside a swc library, made and compiled by Flash Pro 6. it's just a small ball. the registration point of it starts in the middle if it matters.

Problem is, they start rather smoothly, then you can see them lagging a bit, sort of dancing while keep moving, then a second after you see them running smoothly again, and the problem repeats itself.

I tried placing faster timers instead of ENTER_FRAME event, but I can still see some lagging. I also tried setting the configuration of FlashDevelop to release mode instead of debug and it didn't help too. If I could share the entire code somewhere so you'd see the swf I will, but for now on I hope this code alone helps... Thank you for your time.

Aucun commentaire:

Enregistrer un commentaire