2014-01-11 77 views
0

我幾乎全新的OOP,我只是不明白如何調用另一個類中的方法。我試圖從自定義類中調用Main.as中的方法,但它總是以「調用可能未定義的方法」錯誤的形式出現,而我不知道解決方法。AS3 - 調用類之間的方法

Main.as代碼:

package { 

import flash.display.MovieClip; 

public class Main extends MovieClip { 

    public var titleScreen:TitleScreen = new TitleScreen(); 
    public var feedMeShibe:FeedMeShibe = new FeedMeShibe; //These are exported 
    public var milkbone:MilkboneItem = new MilkboneItem; //actionscript symbols 
    public var openMouthArea:OpenMouthArea = new OpenMouthArea; //in the library 

    public function Main() { 
     titleScreen.x = 350; 
     titleScreen.y = 250; 
     addChild(titleScreen); 
    } 
    public function addShibe(shibeX:Number, shibeY:Number, shibeSize:Number):void { 
     feedMeShibe.x = shibeX; 
     feedMeShibe.y = shibeY; 
     feedMeShibe.width = feedMeShibe.width*shibeSize; 
     feedMeShibe.height = feedMeShibe.height*shibeSize; 
     addChild(feedMeShibe); 
    } 

    public function addMilkbone(milkboneX:Number, milkboneY:Number, milkboneSize:Number):void { 
     milkbone.x = milkboneX; 
     milkbone.y = milkboneY; 
     milkbone.width = milkbone.width*milkboneSize; 
     milkbone.height = milkbone.height*milkboneSize; 
     addChild(milkbone); 
    } 
    public function addOpenMouthArea(OMAX:Number, OMAY:Number, OMAW:Number, OMAH:Number):void { 
     openMouthArea.x = OMAX; 
     openMouthArea.y = OMAY; 
     openMouthArea.width = OMAW; 
     openMouthArea.height = OMAH; 
     addChild(openMouthArea); 
    } 

} 

}

TitleScreen.as代碼:

package { 

import flash.display.MovieClip; 
import flash.events.Event; 
import fl.transitions.Tween; 
import fl.transitions.easing.*; 
import fl.transitions.TweenEvent; 


public class TitleScreen extends MovieClip { 


    public function TitleScreen() { 
     createListeners(); 
    } 
    private function createListeners():void { 
     this.addEventListener(Event.ENTER_FRAME, stopFrame); 
    } 
    public function stopFrame(e:Event):void { 
     if (this.currentFrame == 510){ 
      this.removeEventListener(Event.ENTER_FRAME, stopFrame); 
      this.stop(); 
      addShibe(100, 100, 0.5); //How do I 
      addMilkbone(50, 50, 0.6); //access the Main class 
      addOpenMouthArea(200, 200, 1, 1); //with these? 
     } 

    } 

} 

}

我通常不在線提問,但我米在我的繩子在這裏結束。我完全陷入困境,瀏覽教程和之前的在線問題只會讓我更加困惑。任何幫助將不勝感激。

回答

2

最簡單的方法是讓一個類引用另一個類。假設你有一個開關和一個燈泡。開關可以告訴燈泡打開和關閉燈。

下面是它如何可能看起來像一個簡約的例子:

var bulbInstance:Bulb = new Bulb(); 

var switchInstance:LightSwitch = new LightSwitch(); 
switchInstance.bulbReference = bulbInstance; 

現在你有你的開關類引用一個燈泡。從它裏面你可以調用公共方法並訪問Bulb類的公共變量。 不要忘記在LightSwitch類中創建一個公共變量bulbReference。

有許多方法來形成你的代碼的元素,打破強的依賴性,使你的代碼之間的依賴關係:可擴展性,可重用性和可維護性。要了解它,請查找設計模式。有寫關於這個話題偉大的書:http://shop.oreilly.com/product/9780596528461.do

但有在互聯網上免費的話題了大量的材料。

0

如果我沒有記錯的所有你需要做的就是

Main.addShibe(100, 100, 0.5); //How do I Main.addMilkbone(50, 50, 0.6); //access the Main class Main.addOpenMouthArea(200, 200, 1, 1); //with these?