Saturday, May 17, 2008

Repeating processes and animations

During the work we meet some problems with repeating some processes or animations periodically. For exampl we have some animation, which we want to loop or some process. Here is the implementation for it. I will first write down the actionscript 2 implementation of it using non-documented Animation class, which is just a wrapper of a movieClip, with more functionality like start(), stop() and which casts "COMPLETED" event.
We should write a class for dynamically repeat the animation until the stop method hasn't been called.


//AS 2.0 implementation
class AnimRepeater{

    private var _isStarted : Boolean;

    private var _clipName : MovieClip;

    private var _animationLoop : Animation;



    public function AnimRepeater(clipName : String) {

        _clipName = clipName;

    }



    public function start() : Void {

        if (!_isStarted) {

           _isStarted = true;

           updateAnim();

        }

    }



    public function stop() : Void {

        if (_isStarted) {

           _isStarted = false;

        }

    }



    private function updateAnim() : Void {

       if (_isStarted) {

           var autoDelete : Boolean = true;

           _animationLoop = new Animation(_clipName, "animName", autoDelete);

           _animationLoop.addEventListener(Animation.FINISHED, Delegate.create(this, updateAnim));

           _animationLoop.start();

        }

    }


}




For C# let's add some flexibility. We should use a IProcess interface, which should be used to controll the process which should be repeated.

public delegate void ProcessEventHandler(IProcess argProcess, EventArgs argEventArgs);

interface IProcess

{

    public event ProcessEventHandler Finished;

    public void start();

    public void stop();

}



public class ProcessRepeater : IProcess

{

    protected bool isStarted;

    protected IProcess processToRepeat;

    public event ProcessEventHandler Finished;



    public ProcessRepeater(IProcess argProcess)

    {

       processToRepeat = argProcess;

       isStarted = false;

    }



    public void start()

    {

       if (!isStarted)

       {

          isStarted = true;

          updateProcess();

       }

    }



    public void stop()

    {

       if (isStarted)

       {

          isStarted = false;

          processToRepeat.stop();

          processToRepeat.Finished -= new ProcessEventHandler(updateProcess);

       }

    }



    protected void updateProcess()

    {

       if (isStarted)

       {

          processToRepeat.Finished += new ProcessEventHandler(updateProcess);

          processToRepeat.start();

       }

    }



    private void updateProcess(IProcess argProcess, EventArgs argEventArgs)

    {

       updateProcess();

    }

}

Post a Comment