class GamView extends ui.gameUI{ private mole:Array<Mole>; private number:number = 9; //定義鼠洞的個數 private score:number; //定義初始化分數 private moleShowTime:number = 600; //聲明老鼠出現速度(與時間關聯,時間越少速度越快) constructor(){ super(); this.mole = new Array<Mole>(); //注意,數組聲明還不能直接使用,要先new一下,而且不要再循環里面new,不然會一直出現第一個 this.timeBar.value = 1; //初始化時間進度條為1,即為滿格 this.score = 0; //初始化分數為0\ // this.scorenumber.dataSource = {item6:{index:3}}; //這里需要建立一個分數的處理,來和后台的受擊打hit方法來進行數據交互 //Handler處理器的參數說明:第一個this表示當前的作用域,是當前累;第二個參數,this.setScore表示回調后執行當前類的setScore方法 //第三個表示參數數組,這里不需要,所以是null;第四個參數false表示不是只調用一次,因為每次擊打都要調用這個處理器。默認是once,只執行一次 var hitCallBack:Laya.Handler = Laya.Handler.create(this,this.setScore,null,false); //this.mole = new Mole(this.normal,this.hit,131); // this.mole.Show(); for(var i:number=0;i<this.number;i++){ var box:Laya.Box = this.getChildByName("item"+i) as Laya.Box; //注意,這里的node是不是一個box類型,所以要用as轉成box類型 var moleObj:Mole = new Mole(box.getChildByName("normal") as Laya.Image,box.getChildByName("hit") as Laya.Image,box.getChildByName("scoreImg") as Laya.Image,123,hitCallBack);//這里也要用as轉成image類型 this.mole.push(moleObj);//把對象push放到array容器里面 } } }
在這里例子中,我們先要新建一個Gamview類來繼承頁面的ui類ui.gameUI,不能直接對頁面ui.gameUI類進行操作。然后我們重點看里面的那個for循環
這里就有涉及到元素節點的獲取,這里用的是getChildByName()方法獲得節點(注意:類型不一致的要用as來做類型轉換,如上代碼),還可以通過一下的方法獲得元素節點: