Search code examples
actionscript-3flashdevelop

Function in Sprite does not run to display


Function X1 simply does not run- no trace result and programme so basic.
Board.as is called- I checked.
Simple sprite display not working.

Main.as

package 
{
    import flash.display.Bitmap;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.*;
    import flash.text.TextField;
    import flash.ui.Keyboard;
    import Start;
    import Board;
    /**
     * ...
     * @author Michael
     */

    public class Main extends Sprite 
    {

        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init():void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);

            var Board1:Sprite = new Board();   
            stage.addChild(Board1);


            Board1.visible = true;

            var Start1:Sprite = new Start();
            Start1.x = 32;
            Start1.y = 32;
            addChild (Start1);
            stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
            function myKeyDown(e:KeyboardEvent):void{
            if (e.keyCode ==Keyboard.SPACE) 
            {
            removeChild(Start1);
            Start1 = null;  
            }


            } 
}

Board.as

package 
{
    import flash.display.Bitmap;
    import flash.display.Graphics;
    import flash.display.Sprite;


    /**
     * ...
     * @author Michael
     */
    public class Board extends Sprite
    {
    [Embed(source="../lib/Board.jpg")]
    private var BoardClass :Class

    public function X1():void  
    {
        var boardclass:Bitmap = new BoardClass () as Bitmap;
    trace("Project is running fine!");
        this.addChild(boardclass);

    }
    }



}

Solution

  • You are not calling the function X1(). Change the code part in your Main.as class where you create the Board to this:

    var Board1:Sprite = new Board(); 
    Board1.X1();
    stage.addChild(Board1);
    

    A few more tips for your code:

    1) You don't need Board1.visible = true;, it's visible by default

    2) Change the name of Board1 to board1 or just board. It's a standard to call classes with first capital letter.

    EDIT:

    If you want X1() to be run as you create the object, call this function in the constructor of Board.as. Constructor is a function that is run when you create an object. For Board.as it would be like this:

    public function Board():void
    {
    
       X1(); // this function will be called when you create a new Board object
    }