2011-10-08 46 views
0

以下是使用AIR SDK 3.0從Flash Builder 4.5構建的MXML代碼。使用Starling框架創建2D動畫並想知道如何在不創建Game的新實例的情況下調用addText函數?調用AS3包中的函數

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); 
     } 
    } 
} 

回答

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未在該方法中定義。您將無法訪問靜態方法中類的實例變量。