在AS3包中调用一个函数

时间:2011-10-08 11:33:54

标签: flash flex actionscript air starling-framework

以下是使用Flash Builder 4.5和AIR SDK 3.0构建的MXML代码。使用Starling框架创建2D动画,并想知道如何在不创建addText的新实例的情况下调用Game函数?

main.mxml是一个主要的应用程序:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       applicationComplete="windowedapplication1_applicationCompleteHandler(event)"
                       backgroundAlpha="0" showStatusBar="false" height="700" frameRate="60" width="800">
    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import starling.core.Starling;

            private var mStarling:Starling;

            protected function windowedapplication1_applicationCompleteHandler(event:FlexEvent):void
            {

                stage.scaleMode = StageScaleMode.NO_SCALE;
                stage.align = StageAlign.TOP_LEFT;
                this.y=0;

                mStarling = new Starling(Game, stage);
                mStarling.start();
            }

            private function gaa():void {
                //How to access addText() in Games.as?
            }

        ]]>
    </fx:Script>
    <s:Button x="693" y="19" label="Add Text" click="gaa()"/>

</s:WindowedApplication>

Games.as是一个创建精灵的包:

package 
{
    import scenes.Scene;
    import starling.display.Button;
    import starling.display.Image;
    import starling.display.Sprite;
    import starling.events.Event;
    import starling.textures.Texture;

    public class Game extends Sprite
    {
        private var mMainMenu:Sprite;
        private var mCurrentScene:Scene;

        public function Game()
        {
            var bg:Image = new Image(Assets.getTexture("Background"));
            addChild(bg);

            mMainMenu = new Sprite();   //create new sprite
            addChild(mMainMenu);

        }
        public function addText():void {
            var logo:Image = new Image(Assets.getTexture("Logo"));  //add logo
            logo.x = int((300 - logo.width) / 2);
            logo.y = 50;
            mMainMenu.addChild(logo);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

  

如何在不创建新实例的情况下调用addText函数   游戏?

您需要使用静态方法在类上调用方法而不创建它的实例。像这样:

    public static function addText():void {
        var logo:Image = new Image(Assets.getTexture("Logo"));  //add logo
        logo.x = int((300 - logo.width) / 2);
        logo.y = 50;
        mMainMenu.addChild(logo);
    }

然后你可以调用这样的方法:

Games.addText()

当然,编写的方法会引发错误;因为mMainMenu未在方法中定义。您将无法访问静态方法内的类上的实例变量。