Search code examples
actionscript-3flashactionscript

Initialize the code (in a actionscript file) in a different frame


How can I initialize this game in a differente frame with the function init? I'm working in Actionscript 3.0.

Hope you can help me. Heres the code (the code is in a actionscript file) :

package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event

public class Main extends MovieClip{

    //constants
    const gravity:Number = 1.5;            //gravity of the game
    const dist_btw_obstacles:Number = 300; //distance between two obstacles
    const ob_speed:Number = 8;             //speed of the obstacle
    const jump_force:Number = 15;          //force with which it jumps

    //variables
    var player:Player = new Player();      
    var lastob:Obstacle = new Obstacle();  //varible to store the last obstacle in the obstacle array
    var obstacles:Array = new Array();     //an array to store all the obstacles
    var yspeed:Number = 0;                 //A variable representing the vertical speed of the bird
    var score:Number = 0;                  //A variable representing the score

    public function Main(){
        init();
    }

    function init():void {
        //initialize all the variables
        player = new Player();
        lastob = new Obstacle();
        obstacles = new Array();
        yspeed = 0;
        score = 0;

        //add player to center of the stage the stage
        player.x = stage.stageWidth/2;
        player.y = stage.stageHeight/2;
        addChild(player);

Solution

  • If there are frame (for Adobe Animate projects), use addFrameScript:

    someMC.addFrameScript(2, myFunction);
    
    private function myFunction():void{
      this.stop();
    }
    

    myFunction work if frame 2 would have existed.

    If not, you can use Tween frameworks like TweenLite or TweenMax (Recommended):

    TweenLite.to(mc, 1.5, {onComplete:myFunction});
    function myFunction():void {
        trace("tween finished");
    }
    

    myFunction is run after 1.5 sec