Skip to main content
Inspiring
July 22, 2014
Answered

Sprite animation with ENTER_FRAME

  • July 22, 2014
  • 1 reply
  • 662 views

I have 2 mc in my library (mc_1 and mc_2) and 1 sprite. The mc's are the children of the sprite.

I write this code to put them on stage:

var m1: mc_1 = new mc_1;

var m2: mc_2 = new mc_2;

var g: sprite = new sprite();

m1.x = 0;

m2.x = 60;

g.addChild(m1);

g.addChild(m2);

addChild(g);

Now I want to start an animated switch between these 2 mc's using Event.ENTER_FRAME (m1 goes to the place of m2 and m2 goes to the place of m1 only on x axis). This should happen when I click on m1 or m2. How can I do that?

My function for animation is this:

function movePieces (event:Event) :void

{

     var i: int;

     for (i = 0; i <= 60; i = i +5)

     {

          t1.x = i;

          t2.x = 60 - i;

     }

}


This topic has been closed for replies.
Correct answer Ned Murphy

So, I should do something like this?

function movePieces (event:Event) :void

{

     var i: int = 0;

     if (i <= 60)

     {

         m1.x = i;

          m2.x = 60 - i;

          i = i + 5;

     }

else

{

     removeEventListener(Event.ENTER_FRAME, movePieces);

}

}


function clickPiece(event:MouseEvent)

{

     addEventListener(Event.ENTER_FRAME, movePieces);

}

m1.addEventListener(MouseEvent.CLICK,clickPiece);

m2.addEventListener(MouseEvent.CLICK,clickPiece);


Something like it, except you want i to be declared outside the function, otherwise it equals 0 easch time the function executes.  Also, you might want to put a conditional on the line that adds the event listener in the clickPiece function so that it only creates the listener if one doesn't already exist.

1 reply

Ned Murphy
Legend
July 22, 2014

You need to target m1 and m2, not t1 and t2.  Also, make sure you create the ENTER_FRAME listener.

gibsyAuthor
Inspiring
July 22, 2014

I wrote by mistake t1 and t2

So, I should add an event listener to m1 and m2 for mouse click like this?

m1.addEventListener(MouseEvent.CLICK,movePieces);

m2.addEventListener(MouseEvent.CLICK,movePieces);

And where should I place the ENTER_FRAME listener?

Ned Murphy
Legend
July 22, 2014

The movePieces function is for the ENTER_FRAME listener, not for the clicking.  The ENTER_FRAME listener will start executing as soon as you create it, so if you want it to start when m1 or m2 gets clicked then you should do so in the event handler function for the clicking.