天天看點

Egret官方案例學習筆記

1.資源記載方式

(1)Egret引擎是2.0.5。

(2)resource/resource.json檔案是:

Egret官方案例學習筆記
Egret官方案例學習筆記
{
    "resources": [
        {
            "name": "bgImage",
            "type": "image",
            "url": "assets/bg.jpg"
        },
        {
            "name": "egretIcon",
            "type": "image",
            "url": "assets/egret_icon.png"
        },
        {
            "name": "description",
            "type": "json",
            "url": "config/description.json"
        }
    ],
    "groups": [
        {
            "name": "demo2",
            "keys": "bgImage,egretIcon"
        }
    ]
}      

View Code

(3)egretProperties.json中的文檔類document_class中的Mian修改為“Demo2”.

(4)Demo2.ts類

Egret官方案例學習筆記
Egret官方案例學習筆記
/**
 *
 * @author 
 *
 */
class Demo2 extends egret.DisplayObjectContainer {
    //測試用的位圖
    private logo: egret.Bitmap;
    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.startGame,this);
    }
    //遊戲啟動後,會自動執行此方法
    public startGame(): void { 
        this.loadResource();
    }
    //加載所需資源
    private loadResource(): void
    {      //使用所需資源
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoadComplete,this);
          //loadConfig的第二個參數用于指定資源根目錄
        RES.loadConfig("resource/resource.json","resource/");
        RES.loadGroup("demo2");
    }
    //加載完畢後即可使用
    private onResourceLoadComplete(event: RES.ResourceEvent): void
    { 
        this.logo = new egret.Bitmap();//建立位圖
        this.logo.touchEnabled = true;//可點選
        this.logo.width = this.logo.height = 100;//設定尺寸
        this.logo.scaleX = this.logo.scaleY = 1.5;//設定縮放
        this.logo.rotation = 45;//旋轉
        this.logo.skewX = 45;//斜切
        this.logo.anchorX = 0.5;//設定中心點的位置,實作圍繞中心旋轉
        this.logo.texture = RES.getRes("egretIcon");//設定紋理
        this.addChild(this.logo);//添加到顯示清單
        this.startAnimation();//調用運動函數
    }
    //使用Tween讓位圖做一些運動,并封裝在一個方法内部
    private startAnimation(): void
    { 
        var tw = egret.Tween.get(this.logo);
        //Tween的執行是串行的,方法執行後,傳回自身,這樣4個to相連,其實就是依次執行4次to方法。
        tw.to({ x: 280,y: 0 },400).to({ x: 280,y: 300 },500).to({ x: 0,y:300},500).to({ x: 0,y: 0 },200);
        tw.call(this.startAnimation,this);//最後又調用了一次call,含義是動畫完成後,調用startAnimation方法。其實就是産生循環調用的結果,動畫會一直執行下去。
    }
        
    
}      

View Code

2.普通文本

(1)Egret引擎是2.05

(2)egretProperties.json中的文檔類document_class中的Mian修改為“Demo2”.

(3)Demo2.ts類 

Egret官方案例學習筆記
Egret官方案例學習筆記
/**
 *
 * @author 
 *
 */
class Demo2 extends egret.DisplayObjectContainer {

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.startGame,this);
    }
    //遊戲啟動後,會自動執行此方法。
    //Canvas有fillText和strokeText兩個方法來繪制文本,Egret正式通過這個機制繪制普通文本的。
    public startGame(): void { 
        var label1 = new egret.TextField();//建立TextField執行個體
        label1.fontFamily = "Impact";//設定字型。
        label1.textColor = 0xffffff;//設定顔色,和Flash一樣,設定16進制的數值
        label1.textAlign = "left";//設定文本對齊,可選:left,center,right
        label1.text = "English我是光頭強\n 你是大熊";//用\n來換行
        label1.size = 30;//設定字号
        label1.width = 120;//如果設定寬度,則文本自動換行
        label1.strokeColor = 0xFF0000;//設定描邊顔色,描邊在遊戲中的文字上很常見
        label1.stroke = 2;//設定描邊大小
        //設定坐标
        label1.x = 120;
        label1.y = 100;
        //支援旋轉和斜切
        label1.rotation = 30;
        label1.skewX = 30;
        this.addChild(label1);//添加到顯示清單
    }  
}      

View Code

3.播放音樂

(1)Egret引擎是2.05

(2)egretProperties.json中的文檔類document_class中的Mian修改為“Demo2”.

(3)resource/assets中添加hongqinajin.mp3音樂檔案。resource/resource.json檔案是:

Egret官方案例學習筆記
Egret官方案例學習筆記
{
    "resources": [
        {"name":"sfx_die","type":"sound","url":"assets/hongqianjin.mp3"},
        {
            "name": "description",
            "type": "json",
            "url": "config/description.json"
        }
        
        
    ],
    "groups": [
        {
            "name": "demo2",
            "keys": "bgImage,egretIcon"
        },
        {"name":"demo6","keys":"sfx_die"}
    ]
}      

View Code

(4)Demo2.ts類

Egret官方案例學習筆記
Egret官方案例學習筆記
/**
*
* @author 目前egret支援的音樂格式隻有mp3。和圖檔建立一樣,播放音樂也需要先加載音樂檔案
* 
*
*/
class Demo2 extends egret.DisplayObjectContainer {
  
    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.startGame,this);
    }
    //遊戲啟動後,會自動執行此方法
    public startGame(): void {
        this.loadResource();
    }
    //加載所需資源
    private loadResource(): void {      //使用所需資源
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoadComplete,this);
        //loadConfig的第二個參數用于指定資源根目錄
        RES.loadConfig("resource/resource.json","resource/");
        RES.loadGroup("demo6");
    }
    //加載完畢後就可以對音樂檔案進行播放和停止的操作
    private onResourceLoadComplete(event: RES.ResourceEvent): void {
        var sound:egret.Sound = RES.getRes("sfx_die");//擷取音樂檔案        
        sound.play();//播放音樂檔案
        
        //3秒後音樂播放結束
        egret.setTimeout(function() {
            sound.pause();//音樂播放結束
        },this,3000);//間隔時間為3秒針
        
    }
}      

View Code

4.事件

(1)Egret引擎是2.05

(2)egretProperties.json中的文檔類document_class中的Mian修改為“Demo2”.

(3)resource/assets中添加hongqinajin.mp3音樂檔案。resource/resource.json檔案是:

Egret官方案例學習筆記
Egret官方案例學習筆記
{
    "resources": [
        {
            "name": "bgImage",
            "type": "image",
            "url": "assets/bg.jpg"
        },
        {
            "name": "egretIcon",
            "type": "image",
            "url": "assets/egret_icon.png"
        },
        {
            "name": "description",
            "type": "json",
            "url": "config/description.json"
        }
    ],
    "groups": [
        {
            "name": "demo2",
            "keys": "bgImage,egretIcon"
        }
    ]
}      

View Code

(4)Demo2.ts類

Egret官方案例學習筆記
Egret官方案例學習筆記
/**
*
* @author :egret采用了和Flash類似的“事件流”機制。事件的基類是Event,所有的事件類從Event擴充而來。
* Egret中的事件支援冒泡機制,在決定事件的時候決定它是否冒泡,同樣也就有了target和currentTarget之分.
*
*/
class Demo2 extends egret.DisplayObjectContainer {
    
    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.startGame,this);
    }
    //遊戲啟動後,會自動執行此方法
    public startGame(): void {
        this.loadResource();
    }
    //加載所需資源
    private loadResource(): void {      //使用所需資源
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoadComplete,this);
        //loadConfig的第二個參數用于指定資源根目錄
        RES.loadConfig("resource/resource.json","resource/");
        RES.loadGroup("demo2");
    }
    //加載完畢後就可以對檔案操作
    //顯示
    private onResourceLoadComplete(): void
    { 
        var container = new egret.DisplayObjectContainer();
        container.touchChildren = true;
        container.touchEnabled = true;//設定容器是否響應Touch互動
        var bitmap1 = new egret.Bitmap(RES.getRes("egretIcon"));
        bitmap1.name = "myBitmap";
        bitmap1.touchEnabled = true;
        container.addChild(bitmap1);
        container.name = "myContainer";
        container.x = container.y = 100;
        this.addChild(container);
     
        container.addEventListener(egret.TouchEvent.TOUCH_TAP,this.touchHandler,container);
      
    }
    //事件偵聽處理
    private touchHandler(event: egret.TouchEvent): void
    { 
        console.log("dddd"+event.type);
        var msg: string = event.type;
        msg += "\n" + event.stageX + "," + event.stageY;
        msg += "\n" + event.localX+ "," + event.localY;
        msg += "\n" + event.currentTarget.name + "," + event.target.name;
        alert(msg);
       
              
        }
        
        }      

View Code

5.進度條的加載

(1)Egret引擎是2.05

(2)resource/assets中根據resource/resource.json檔案配置相關資源。resource/resource.json檔案是:

Egret官方案例學習筆記
Egret官方案例學習筆記
{
    "groups":[
    {
        "keys":"barbright,bardark",
        "name":"preload"
    },
    {
        "keys":"x1,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x2,x20,x21,x22,x23,x24,x25,x26,x27,x28,x29,x3,x30,x4,x5,x6,x7,x8,x9",
        "name":"x30"
    },
    {
        "keys":"",
        "name":""
    }],
    "resources":[
    {
        "name":"barbright",
        "type":"image",
        "url":"assets/barbright.png"
    },
    {
        "name":"bardark",
        "type":"image",
        "url":"assets/bardark.png"
    },
    {
        "name":"x1",
        "type":"image",
        "url":"assets/x30/x1.png"
    },
    {
        "name":"x10",
        "type":"image",
        "url":"assets/x30/x10.png"
    },
    {
        "name":"x11",
        "type":"image",
        "url":"assets/x30/x11.png"
    },
    {
        "name":"x12",
        "type":"image",
        "url":"assets/x30/x12.png"
    },
    {
        "name":"x13",
        "type":"image",
        "url":"assets/x30/x13.png"
    },
    {
        "name":"x14",
        "type":"image",
        "url":"assets/x30/x14.png"
    },
    {
        "name":"x15",
        "type":"image",
        "url":"assets/x30/x15.png"
    },
    {
        "name":"x16",
        "type":"image",
        "url":"assets/x30/x16.png"
    },
    {
        "name":"x17",
        "type":"image",
        "url":"assets/x30/x17.png"
    },
    {
        "name":"x18",
        "type":"image",
        "url":"assets/x30/x18.png"
    },
    {
        "name":"x19",
        "type":"image",
        "url":"assets/x30/x19.png"
    },
    {
        "name":"x2",
        "type":"image",
        "url":"assets/x30/x2.png"
    },
    {
        "name":"x20",
        "type":"image",
        "url":"assets/x30/x20.png"
    },
    {
        "name":"x21",
        "type":"image",
        "url":"assets/x30/x21.png"
    },
    {
        "name":"x22",
        "type":"image",
        "url":"assets/x30/x22.png"
    },
    {
        "name":"x23",
        "type":"image",
        "url":"assets/x30/x23.png"
    },
    {
        "name":"x24",
        "type":"image",
        "url":"assets/x30/x24.png"
    },
    {
        "name":"x25",
        "type":"image",
        "url":"assets/x30/x25.png"
    },
    {
        "name":"x26",
        "type":"image",
        "url":"assets/x30/x26.png"
    },
    {
        "name":"x27",
        "type":"image",
        "url":"assets/x30/x27.png"
    },
    {
        "name":"x28",
        "type":"image",
        "url":"assets/x30/x28.png"
    },
    {
        "name":"x29",
        "type":"image",
        "url":"assets/x30/x29.png"
    },
    {
        "name":"x3",
        "type":"image",
        "url":"assets/x30/x3.png"
    },
    {
        "name":"x30",
        "type":"image",
        "url":"assets/x30/x30.png"
    },
    {
        "name":"x4",
        "type":"image",
        "url":"assets/x30/x4.png"
    },
    {
        "name":"x5",
        "type":"image",
        "url":"assets/x30/x5.png"
    },
    {
        "name":"x6",
        "type":"image",
        "url":"assets/x30/x6.png"
    },
    {
        "name":"x7",
        "type":"image",
        "url":"assets/x30/x7.png"
    },
    {
        "name":"x8",
        "type":"image",
        "url":"assets/x30/x8.png"
    },
    {
        "name":"x9",
        "type":"image",
        "url":"assets/x30/x9.png"
    }]
}      

View Code

(3)Main.ts

Egret官方案例學習筆記
Egret官方案例學習筆記
class Main extends egret.DisplayObjectContainer { 
    public constructor(){
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
      }
    private onAddToStage(event: egret.Event)
    { 
        //初始化Resource資源記載庫
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE,this.onConfigComplete,this);
        RES.loadConfig("resource/resource.json","resource/");      
    }
    //配置檔案加載完成,開始預加載preload資源庫
    private onConfigComplete(event: RES.ResourceEvent): void
    {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE,this.onConfigComplete,this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.createGameScene,this);
        RES.loadGroup("preload"); 
    }
     //perload 資源組加載結束,建立遊戲場景
    private load: Load;
    private createGameScene(event: RES.ResourceEvent): void
    { 
        RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.createGameScene,this);
        //繪制點選的方塊
        var sp: egret.Sprite= new egret.Sprite();
        sp.graphics.beginFill(0xffffff);
        sp.graphics.drawRect(0,0,100,50);
        sp.x = 10;
        sp.y = 10;
        sp.width = 100;
        sp.height = 50;
        sp.touchEnabled = true;//打開點選方塊中的屬性
        this.addChild(sp);
        
        //文字說明
        var txt1: egret.TextField = new egret.TextField();
        txt1.text = "點選架載第1波30個資源圖檔";
        txt1.x = 120,txt1.y = 10;
        this.addChild(txt1);
        
          //申請一個Load執行個體
        this.load = new Load();
        this.load.x = this.stage.width / 2; this.load.y = 110;
        this.addChild(this.load);
        
           //點選開始加載
        sp.addEventListener(egret.TouchEvent.TOUCH_TAP,this.startLoad,this);
    }
    private startLoad(): void
    { 
        this.load.startLoad();//記載對象load中的startLoad函數
    }
    
}      

View Code

(4)Load.ts

Egret官方案例學習筆記
Egret官方案例學習筆記
class Load extends egret.DisplayObjectContainer
{ 
    private maskRect: egret.Rectangle;//一個九宮格
    private txt: egret.TextField;
    private bright: egret.Bitmap;
    public constructor() { 
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
    }
    public onAddToStage(): void
    { 
        this.x = this.stage.stageWidth / 2;//改變了這個螢幕的中心點的位置,由原來的左上角中的x改為中間點為x的起始值
        //底部的進度條
        var dark: egret.Bitmap = new egret.Bitmap(RES.getRes("bardark"));
        dark.x = -dark.width / 2;
        this.addChild(dark);
        //上面的進度條
        this.bright = new egret.Bitmap(RES.getRes("barbright"));
        this.bright.x = -this.bright.width / 2;
        this.addChild(this.bright);
        
        this.maskRect = new egret.Rectangle(0,0,0,24);//一開始的遮罩為0
        this.bright.mask = this.maskRect;
        
        //加載進度說明
        this.txt = new egret.TextField();
        this.txt.width = 400;
        this.txt.textAlign = "center";
        this.txt.text = "0/30";
        this.txt.x = -200;
        this.txt.y = -40;
        this.addChild(this.txt);
    }
    
    public startLoad(): void
    { 
        //加載載資源結束調用onLoadEnd()
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onLoadEnd,this);
        //加載資源的過程,調用onProgress()
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS,this.onProgress,this);
        RES.loadGroup("x30");//記載資源組
    }
    //記載資源檔案過程中
    public onProgress(event: RES.ResourceEvent): void
    { 
        this.txt.text = event.itemsLoaded.toString() + "/" + event.itemsTotal.toString();//記載過程中的文字
        var per:number = event.itemsLoaded / event.itemsTotal;//記載的百分比。event.itemsLoaded是加載的總量。event.itemsToTal是總共要加載的總量。
        this.maskRect = new egret.Rectangle(0,0,per * 256,24);//遮罩的百分比
        this.bright.mask = this.maskRect;//九宮格指派給bright的mask屬性
    }
    //記載資源檔案結束
    public onLoadEnd(): void
    { 
        this.txt.text = "30/30 記載結束";
    }
}      

View Code

6.本地資料存儲

(1)Egret引擎是2.05。

(2)Main.ts

Egret官方案例學習筆記
Egret官方案例學習筆記
//egret實作了本地存儲的功能。存儲資料需要key和value,都必須是字元串。
class Main extends egret.DisplayObjectContainer{
    
    public constructor() {
        super();
        this.createGameScene();
    }
    
    private createGameScene():void{
        //申請一個文本框
        this.txt = new egret.TextField();
        this.txt.text = "點我";
        this.addChild(this.txt);
        this.touchEnabled = true;//打開文本框的點選屬性
        
        this.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onSave,this);//文本框點選的蔣婷
   
    }
    
    private txt:egret.TextField
    //本案例中的key就是“pro”
    private onSave(e:egret.TouchEvent):void{
        //egret.localStorage.removeItem("pro");删除資料
        //egret.localStorage.clear();//将所有資料清空
        
        var value:string;
        //如果能讀取到資料,就把資料複制給value,就在文本框txt中顯示出來。如果沒有讀取資料,那麼就是文本框就顯示1.
        if(egret.localStorage.getItem("pro"))
        {
            value =egret.localStorage.getItem("pro"); //讀取資料
        }else{
            value="1";
        }
        
        this.txt.text = value;
        var v2:string = (parseInt(value)+1).toString();//每次點選一次,就發生一次監聽,也就相當于本函數執行一次,也就是value的值要加1。
        egret.localStorage.setItem("pro",v2);//把數組v2存儲了在本地了。
    }
    
 
}      

View Code

7.粒子系統

官方給定的粒子系統中檔案非常的亂,現在進行整理如下。

(1)引擎是2.5.4。在官方中下載下傳粒子系統的Particle。注意隻需要其中隻有三個檔案(Particle.d.ts,particle.js,particle.min.js)。不需要其它的檔案了。

(2)将上述中的三個檔案放到檔案夾particle中。放到項目中的libs/modules/中即可。

(3)在egretProperties.json中進行配置。在modules中添加“name”和“path”

Egret官方案例學習筆記
Egret官方案例學習筆記
{
    "native": {
        "path_ignore": []
    },
    "publish": {
        "web": 0,
        "native": 1,
        "path": "bin-release"
    },
    "egret_version": "2.5.4",
    "modules": [
        {
            "name": "egret"
        },
        {
            "name": "game"
        },
        {
            "name": "tween"
        },
                {
            "name": "particle",
           "path": "../libsrc"
        },

        {
            "name": "res"
        }
    
    ]
}      

View Code

不過我郁悶的是path中改為:“path”:"../libs"和“path”:“../libs/modules/particle”都可以。

(4)利用EgretFeather進行制作後得到兩個檔案,一個是png文理和json檔案。拷貝到resource/assets中去,并且在resource.json進行正确的配置,在這裡我相信大家都會。這裡是官方的resource.json配置。

Egret官方案例學習筆記
Egret官方案例學習筆記
{
"resources":
    [
        {"name":"blood","type":"image","url":"assets/particle/blood.png"},
        {"name":"star","type":"image","url":"assets/particle/star.png"},
        {"name":"energy","type":"image","url":"assets/particle/energy.png"},
        {"name":"magic","type":"image","url":"assets/particle/magic.png"},
        {"name":"fireworks_json","type":"json","url":"assets/particle/fireworks.json"},
        {"name":"fire_json","type":"json","url":"assets/particle/fire.json"},
        {"name":"sun_json","type":"json","url":"assets/particle/sun.json"},
        {"name":"jellyfish_json","type":"json","url":"assets/particle/jellyfish.json"}
    ],

"groups":
    [
        {"name":"preload","keys":"blood,star,energy,magic,fireworks_json,fire_json,sun_json,jellyfish_json"}
    ]
}      

View Code

(5)到了這一步驟,配置工作都完成了,下面就是代碼的運用了。

當然首先是加載資源了。

Egret官方案例學習筆記
Egret官方案例學習筆記
class Main extends egret.DisplayObjectContainer {

    /**
     * 加載進度界面
     */
    private loadingView:LoadingUI;

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private onAddToStage(event:egret.Event) {
        //設定加載進度界面
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource資源加載庫
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/resource.json", "resource/");
    }

    /**
     * 配置檔案加載完成,開始預加載preload資源組。
     */
    private onConfigComplete(event:RES.ResourceEvent):void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.loadGroup("preload");
    }

    /**
     * preload資源組加載完成
     */
    private onResourceLoadComplete(event:RES.ResourceEvent):void {
        if (event.groupName == "preload") {
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            this.createGameScene();
        }
    }

    /**
     * preload資源組加載進度
     */
    private onResourceProgress(event:RES.ResourceEvent):void {
        if (event.groupName == "preload") {
            this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal);
        }
    }
//這個上面都在講述加載資源,下面才是粒子系統運用的代碼。
    
    private configList:Array<string> = ["fireworks","fire","sun","jellyfish"];//将所有運用的json檔案放到一個數組中
    private configIndex:number = -1;//标志json檔案是哪一個
    private textureList:Array<string> = ["blood","star","energy","magic"];//将所有的紋理放在一個數組中
    private textureIndex:number = 0;//标志紋理集是哪一個?
    private system:particle.ParticleSystem;//聲明一個粒子系統system
    private btn1:egret.TextField;
    private btn2:egret.TextField;

    /**
     * 建立遊戲場景
     */
    private createGameScene():void {
        
        this.stage.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick, this);

        //設定換效果的圖示
        this.btn1 = new egret.TextField();
        this.btn1.text = "換效果";
        this.addChild(this.btn1);
        this.btn1.x = 180;
        this.btn1.width = 100;
        this.btn1.height = 50;
        this.btn1.touchEnabled = true;
        this.btn1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.changeEffect, this);

        //設定換換紋理的圖示
        this.btn2 = new egret.TextField();
        this.btn2.text = "換紋理";
        this.addChild(this.btn2);
        this.btn2.x = 180;
        this.btn2.y = 50;
        this.btn2.width = 100;
        this.btn2.height = 50;
        this.btn2.touchEnabled = true;
        this.btn2.addEventListener(egret.TouchEvent.TOUCH_TAP, this.changeTexture, this);

        this.changeEffect();//粒子生函數。
    }

    private onClick(event):void {
        if(event.target == this.btn1 || event.target == this.btn2) {//如果點選的不是換紋理圖示和換效果的圖示那麼就傳回函數。
            return;
        }
        this.system.emitterX = event.stageX;//粒子系統的位置時點選時位置。也就是滑鼠點選哪兒,哪兒生成粒子。
        this.system.emitterY = event.stageY;
    }

    private changeEffect():void {
        this.configIndex++;//預設采用fireworks.json紋理集
        if (this.configIndex >= this.configList.length) {//當configIndex大于長度時就采用fireworks.json這個紋理集
            this.configIndex = 0;
        }
        var s = this.configList[this.configIndex];//将json複制給s
        var textureS = this.textureList[this.textureIndex];//将紋理集複制給textureS
        var texture = RES.getRes(textureS);//擷取紋理集
        var config = RES.getRes(s + "_json");//擷取json檔案。

        if (this.system) {//如果存在了粒子系統,
            this.system.stop();//粒子系統停止制造
            this.removeChild(this.system);//移除粒子系統
        }

        this.system = new particle.GravityParticleSystem(texture, config);//生成一個粒子系統
        this.addChild(this.system);//粒子系統放到舞台上,否則就不能顯示
        this.system.start();//粒子系統開始啟動
    }

    private changeTexture():void {//改變紋理集
        this.textureIndex++;//紋理集增加1
        if (this.textureIndex >= this.textureList.length) {//如果textureIndex數目超過其數組長度,那麼就複制為0,也就是從頭開始
            this.textureIndex = 0;
        }
        var s = this.textureList[this.textureIndex];//擷取紋理的名字
        var texture = RES.getRes(s);//擷取紋理
        this.system.changeTexture(texture);//粒子系統改變紋理。
    }
}      

View Code

(6)粒子系統中一些重要屬性和方法。

ParticleSystem:

(I)publc emissionTime:number=-1;粒子出現的時間,機關是毫秒,取值範圍是(0,Number.MAX_VALUE],-1表示無限時間。如果你希望粒子系統之存在幾秒毫秒時間,一定要設定。不然粒子系統一定都在建立。

(II)public emitterX:number=0;public emitterY:number=0;也就是粒子系統産生(出現)的位置。

8.callLater()方法

(1)egret.全局函數下定義

(2)public callLater(method:Function,thisObject:any,...args):void

功能:延遲函數到螢幕重繪前執行。

參數:method:Function--要延遲執行的函數

         thisObject:any---回調函數的this引用

    ...args--函數參數清單

(3)

Egret官方案例學習筆記
Egret官方案例學習筆記
private label: egret.TextField;
    private createScene(): void {
        //建立TextField對象
        this.label = new egret.TextField();
        //設定文本顔色
        this.label.textColor = 0xFF0000;
        //設定字号
        this.label.size = 30;
        //設定顯示文本
        this.label.text = "Hello Egret";
        //添加到顯示清單
        this.addChild(this.label);
        
        console.log("beforCallLater");
        //使用callLater實作延遲函數
        egret.callLater(this.onCallLater,this);
        console.log("afterCallLater");
    }
    private onCallLater(): void
    { 
        console.log("onCallLater");
        this.label.text = "callLater";
    }      

View Code

(4)結果:

列印:

beforCallLater

afterCallLater

onCallLater

螢幕上顯示的内容是   callLater

9.getDefinitionByName()方法

(1)egret.全局函數下定義

(2)public getDefinitionByName(name:string):any

功能:傳回name參數指定的類的類對象引用

參數:name:string---類的名稱

(3)

Egret官方案例學習筆記
Egret官方案例學習筆記
private createScene(): void {
        console.log(egret.getDefinitionByName("egret.DisplayObject"));//egret.DisplayObject對象
        console.log(egret.getDefinitionByName("egret.Nothing"));//null
            
        var cls: any = egret.getDefinitionByName("egret.Shape");
        var shape: egret.Shape = new cls();
        shape.graphics.beginFill(0xff00000);
        shape.graphics.drawRect(0,0,100,100);
        shape.graphics.endFill();
        shape.x = shape.y = 100;
        this.addChild(shape);
    }      

View Code

(4)結果

列印:

Egret官方案例學習筆記
Egret官方案例學習筆記
function DisplayObject() {
            _super.call(this);
            /**
             * @private
             * 能夠含有子項的類将子項清單存儲在這個屬性裡。
             */
            this.$children = null;
            /**
             * @private
             */
            this.$parent = null;
            /**
             * @private
             */
            this.$stage = null;
            /**
             * @private
             * 這個對象在顯示清單中的嵌套深度,舞台為1,它的子項為2,子項的子項為3,以此類推。當對象不在顯示清單中時此屬性值為0.
             */
            this.$nestLevel = 0;
            /**
             * @private
             */
            this.$visible = true;
            /**
             * @private
             * cacheAsBitmap建立的緩存位圖節點。
             */
            this.$displayList = null;
            /**
             * @private
             */
            this.$alpha = 1;
            this.$touchEnabled = DisplayObject.defaultTouchEnabled;
            /**
             * @private
             */
            this.$scrollRect = null;
            /**
             * @private
             */
            this.$blendMode = 0;
            /**
             * @private
             * 被遮罩的對象
             */
            this.$maskedObject = null;
            /**
             * @private
             */
            this.$mask = null;
            /**
             * @private
             */
            this.$maskRect = null;
            /**
             * @private
             */
            this.$parentDisplayList = null;
            /**
             * @private
             * 是否需要重繪的标志,此屬性在渲染時會被通路,是以單獨聲明一個直接的變量。
             */
            this.$isDirty = false;
            /**
             * @private
             * 這個對象在舞台上的整體透明度
             */
            this.$renderAlpha = 1;
            /**
             * @private
             * 相對于顯示清單根節點或位圖緩存根節點上的矩陣對象
             */
            this.$renderMatrix = new egret.Matrix();
            /**
             * @private
             * 此顯示對象自身(不包括子項)在顯示清單根節點或位圖緩存根節點上的顯示尺寸。
             */
            this.$renderRegion = null;
            this.$displayFlags = 880 /* InitFlags */;
            this.$DisplayObject = {
                0: 1,
                1: 1,
                2: 0,
                3: 0,
                4: 0,
                5: "",
                6: new egret.Matrix(),
                7: new egret.Matrix(),
                8: new egret.Matrix(),
                9: new egret.Rectangle(),
                10: new egret.Rectangle(),
                11: false,
                12: 0,
                13: 0,
                14: NaN,
                15: NaN //explicitHeight,
            };
        }
null      

View Code

螢幕上顯示一個紅色的正方形

10.getQualifiedClassName()方法

(1)egret.全局函數下定義

(2)public getQualifiedClassName(value:any):string

功能:傳回對象的完全限定類名。

參數:value:any--需要完全限定類名稱的對象,可以将任何JavaScript值傳遞給此方法,包括所有可用的JavaScript類型、對象執行個體、原始類型(如number)和類對象。

傳回:包括完全限定類名稱的字元串。

(3)

Egret官方案例學習筆記
Egret官方案例學習筆記
private createScene(): void {
        console.log(egret.getQualifiedClassName(egret.DisplayObject));//egret.DisplayObject
        console.log(egret.getQualifiedClassName(window));//Window
    }      

View Code

(4)結果:

egret.DisplayObject

Window

11.音頻播放器

(1)Egret引擎2.5.4,建立Egret EUI項目

(2)asset中拷貝音樂,并在default.res.json中配置

(3)Main.ts

Egret官方案例學習筆記
Egret官方案例學習筆記
/*
* egret2.5 音頻播放測試 點選播放按鈕從頭播發 播放狀态下可以暫停和恢複播發。 循環開關開啟講循環播放。
*/

class Main extends eui.UILayer {
    protected createChildren(): void { 
        super.createChildren();
        //eui.Theme 皮膚主題
        var theme = new eui.Theme("resource/default.thm.json",this.stage);
        theme.addEventListener(egret.Event.COMPLETE,this.onLoad,this);
    }
    private onLoad() { 
        var appui = new SoundUI();
        appui.horizontalCenter = 0;
        this.addChild(appui);
    }
}      

View Code

SoundUI.ts

Egret官方案例學習筆記
Egret官方案例學習筆記
/**
 * 播放器的UI界面,包括播放,暫停,設定音量等
 */
class SoundUI extends eui.UILayer { 
   
    private fontSize = 22;
    public constructor() { 
        super();
        //Panel類定義一個容器,該容器為其子代提供标題欄、關閉按鈕、可移動區域和内容區域
        var panel = new eui.Panel();
        panel.horizontalCenter = 0;
        panel.verticalCenter = 0;
        panel.title = "播放器測試";//标題欄中顯示的标題
        panel.width = 400;
        panel.height = 400;
        
        this.addChild(panel);
        
        var music = new SoundTest();
        
        //Label是可以呈現一行或多行統一格式文本的UI元件
        var volumenLabel = new eui.Label();
        volumenLabel.text = "音量";
        volumenLabel.textColor = 0x0205cc;
        volumenLabel.size = this.fontSize;
        volumenLabel.x = 5;
        volumenLabel.y = 210;
        panel.addChild(volumenLabel);
        
        //使用HSlider(水準滑塊)控件,使用者可通過在滑塊軌道的端點之間移動滑塊來選擇值。
        var slider = new eui.HSlider();
        slider.maximum = 100;//最大有效值
        slider.minimum = 0;//最小有效值,規定value屬性的值不能夠低于的最小值
        slider.value = 80;//此範圍的目前值
        slider.liveDragging = true;//如果為true,則将在沿着軌道拖動滑塊時,而不是在釋放滑塊按鈕時,送出此滑塊的值
        slider.addEventListener(egret.Event.CHANGE,(e: egret.Event) => {
            console.log(slider.pendingValue);//pendingValue:觸摸結束時滑塊将具有的值
            music.setVolume(slider.pendingValue);
        },this);
        slider.x = 70;
        slider.y = 210;
        slider.width = 200;
        panel.addChild(slider);
        
        //toggleButton元件定義切換按鈕。
        var play = new eui.ToggleButton();
        play.label = "播放";
        play.x = 50;
        play.y = 70;
        play.addEventListener(egret.Event.CHANGE,(e: egret.TouchEvent) => {
            if(play.selected) {//selected:boolean 按鈕處于按下狀态時為true,而按鈕處于彈起狀态時為false
                music.play();
            } else {
                music.stop();
            }
        },this);
        panel.addChild(play);
        
        //toggleSwitch表示一個開關元件
        var loop = new eui.ToggleSwitch();
        loop.label = "循環";
        loop.x = 150;
        loop.y = 70;
        loop.addEventListener(egret.Event.CHANGE,(e: egret.Event) => {
            if(loop.selected) {//selected:boolean 按鈕處于按下狀态時為true,而按鈕處于彈起狀态時為false
                music.setLoop(-1);
            } else {
                music.setLoop(1);
            }
        },this);
        panel.addChild(loop);
        
        var looplable = new egret.TextField();
        looplable.text = "循環";
        looplable.x = loop.x;
        looplable.y = loop.y + 27;
        looplable.size = 20;
        looplable.textColor = 0x2103cc;
        panel.addChild(looplable);
        
        var pause = new eui.Button();
        pause.label = "暫停";
        pause.x = 50;
        pause.y = 120;
        pause.addEventListener(egret.TouchEvent.TOUCH_TAP,(e: egret.TouchEvent) => {
            music.pouse();
        },this);
        panel.addChild(pause);

        var resume = new eui.Button();
        resume.label = "恢複";
        resume.x = 150;
        resume.y = 120;
        resume.addEventListener(egret.TouchEvent.TOUCH_TAP,(e: egret.TouchEvent) => {
            music.resume();
        },this);
        panel.addChild(resume);

        var timelable = new eui.Label();
        timelable.text = "播放時間: " + music.showPosition().toFixed(4);
        timelable.textColor = 0x0205cc;
        timelable.size = this.fontSize;
        timelable.x = 5;
        timelable.y = 250;
        panel.addChild(timelable);
        
        this.addEventListener(egret.Event.ENTER_FRAME,(e: egret.Event) => {
            timelable.text = "播放時間:" + music.showPosition().toFixed(4) + "s";
        },this);
        
        var inputBg = new eui.Image("resource/assets/CheckBox/checkbox_select_up.png");
        inputBg.scale9Grid = new egret.Rectangle(2,2,19,19);
        inputBg.width = 300;
        inputBg.height = 25;
        inputBg.x = 70;
        inputBg.y = 300
        panel.addChild(inputBg);
        
        //可編輯文本,用于顯示、滾動、選中和編輯文本
        var inputUrl = new eui.EditableText();
        inputUrl.width = inputBg.width;
        inputUrl.height = inputBg.height;
        inputUrl.x = inputBg.x;
        inputUrl.y = 300;
        inputUrl.textColor = 0x000000;
        inputUrl.size = this.fontSize;
        inputUrl.text = "輸入外部音頻位址";
        panel.addChild(inputUrl);
        
        inputUrl.addEventListener(egret.FocusEvent.FOCUS_IN,(e: egret.FocusEvent) => {
            inputUrl.text = "";
        },this);
        
        var button: eui.Button = new eui.Button();
        button.label = "加載";
        button.x = 5;
        button.y = inputUrl.y;
        button.scaleX = 0.6;
        button.scaleY = 0.55;
        panel.addChild(button);
        
        button.addEventListener(egret.TouchEvent.TOUCH_TAP,(e: egret.TouchEvent) => {
            if(inputUrl.text === "先輸入外部音頻位址")
                waring.text = "請先輸入位址後再載入";
            else
                music.setUrl(inputUrl.text);
        },this);
        music.addEventListener(egret.IOErrorEvent.IO_ERROR,(e: egret.IOErrorEvent) => {
            waring.text = e.data;
            waring.textColor = 0xcc1122;
        },this);
        
        var waring: eui.Label = new eui.Label();
        waring.text = "5";
        waring.horizontalCenter = 0;
        waring.textColor = 0x11cc22;
        waring.size = 18;
        waring.fontFamily = "KaiTi";
        waring.y = 350;
        panel.addChild(waring);
    }
   
}      

View Code

SoundTest.ts

Egret官方案例學習筆記
Egret官方案例學習筆記
class SoundTest extends egret.Sprite {

    public constructor (url?:string) {
        
        super();
        
        if(url)
            this.soundURL = url;

        this.sound = new egret.Sound();//建立一個Sound對象
        this.loadSound();
    }

    private sound:egret.Sound; 
    
    private soundURL:string = "resource/sound/soundtest.mp3";

    private soundChannel:egret.SoundChannel;//SoundChannel類控制引用程式中的聲音
    //預設播放位置,從頭開始的
    private positon:number = 0;
    //預設不循環,設定為負數循環
    private loop:number = 1;
    //目前狀态0位空,1位播放,2位暫停, 3表示加載完成,4表示加載失敗
    private status:number = 0;
    //加載音頻
    private loadSound() {
        this.sound.once(egret.Event.COMPLETE,this.loadComplete,this);
        this.sound.once(egret.IOErrorEvent.IO_ERROR,this.onLoadErr,this);
        this.sound.load(this.soundURL);//啟動從指定URL加載外部音頻檔案的過程
    }
    //加載音頻完成
    private loadComplete (e:egret.Event) {
        this.status = 3;
        var waring:string = "加載完成";
        console.log(waring);
        this.dispatchEventWith(egret.Event.COMPLETE,false,waring);
    }
    //加載音頻失敗
    private onLoadErr (e:egret.IOErrorEvent) {
        this.status = 4;
        var waring:string = "加載失敗"+this.soundURL;
        console.log(waring);
        this.dispatchEventWith(egret.IOErrorEvent.IO_ERROR,false,waring);
    }
    //設定url并重新加載
    public setUrl(url:string) {
        this.soundURL = url;
        this.loadSound();
    }
    //設定循環
    private looped(e:egret.Event){
        this.positon = 0;
        this.status = 0;
        this.play();
    }
    //擷取狀态
    public getStatus() {
        return this.status;
    }
    //設定音量
    public setVolume (volume:number) {
        if(this.status === 1)
            this.soundChannel.volume = volume / 100;//volume:number  音量範圍從0(靜音)至1(最大量)
    }
    //顯示播放時間
    public showPosition ():number {

        if(this.status === 1)
            this.positon = this.soundChannel.position;//position當播放聲音時,position屬性表示聲音檔案中目前播放的位置(以秒為機關)
        return this.positon;
    }

    public play() {
        if(this.status === 4){
            this.loadSound();
            return;
        }
        this.status = 1;
        if(this.soundChannel) this.soundChannel.stop();//stop();void 停止在該聲道中播放聲音
        console.log(this.positon);
        this.soundChannel = this.sound.play(this.positon,this.loop);
        console.log(this.status);
    }
    public setLoop(loop:number = 1):number{
        this.loop = loop;
        if(loop < 0){
            this.soundChannel.addEventListener(egret.Event.SOUND_COMPLETE,this.looped,this);
        } else{
            return loop;
        }
        
    }
    public pouse () {
        console.log(this.status);
        if(this.status === 1){
            this.positon = this.soundChannel.position;
            this.soundChannel.stop();
            this.status = 2;
        }
        
        return this.positon;
    }
    public resume () {
        if(this.status === 2)
          this.play();
    }
    public stop () {
        this.positon = 0;
        this.soundChannel.stop();
    }
}      

View Code

 12.視訊播放器

(1)Egret引擎2.5.4,建立Egret EUI項目

(2)確定加載位址中有視訊。

(3)main.ts

Egret官方案例學習筆記
Egret官方案例學習筆記
class Main extends eui.UILayer { 
    protected createChildren(): void { 
        super.createChildren();
        var theme = new eui.Theme("resource/default.thm.json",this.stage);
        
        this.addChild(new VideoTest());
    }
}      

View Code

VideoTest.ts

Egret官方案例學習筆記
Egret官方案例學習筆記
/**
 *
 * @author Video允許在應用程式中使用視訊
 *
 */
class VideoTest extends egret.DisplayObjectContainer {
    private video: egret.Video;
    
    public constructor() {
        super();
        this.video = new egret.Video();
        this.video.x = 0;//視訊坐标x
        this.video.y = 0;//視訊坐标y
        this.video.width = 640;//視訊寬
        this.video.height = 320;//視訊高
        this.video.fullscreen = false;//設定是否全屏(暫不支援移動裝置)
        this.video.poster = "resource/post.png";//設定loding圖  poster:string  視訊加載前,或者在不支援将video畫canvas的裝置上,想要顯示的視訊截圖位址在
        this.video.load("http://media.w3.org/2010/05/sintel/trailer.mp4");//load(url:sting):void啟動從指定URL加載外部視訊檔案的過程
        this.addChild(this.video);//将視訊添加到舞台
        //監聽視訊加載完成
        this.video.once(egret.Event.COMPLETE,this.onLoad,this);
        //監聽視訊加載失敗
        this.video.once(egret.IOErrorEvent.IO_ERROR,this.onLoadErr,this);
    }
    private onLoad(e: egret.Event) { 
        var btnPlay: eui.Button = new eui.Button();
        btnPlay.label = "播放";
        btnPlay.x = this.video.x + 20;
        btnPlay.y = this.video.y + this.video.height + 20;
        this.addChild(btnPlay);
        btnPlay.addEventListener(egret.TouchEvent.TOUCH_TAP,this.play,this);
        
        var btnPause: eui.Button = new eui.Button();
        btnPause.label = "暫停";
        btnPause.x = btnPlay.x + btnPlay.width + 20;
        btnPause.y = btnPlay.y;
        this.addChild(btnPause);
        btnPause.addEventListener(egret.TouchEvent.TOUCH_TAP,this.pause,this);
        
        var volume: eui.HSlider = new eui.HSlider();
        volume.x = btnPlay.x;
        volume.y = btnPlay.y + btnPlay.height + 20;
        this.addChild(volume);
        volume.value = 100;
        volume.maximum = 100;
        volume.minimum = 0;
        volume.width = 200;
        volume.addEventListener(egret.Event.CHANGE,this.setVoluem,this);
        
        var screenSwitcher: eui.ToggleSwitch = new eui.ToggleSwitch();
        screenSwitcher.label = "全屏";
        screenSwitcher.x = btnPause.x + btnPause.width + 20;
        screenSwitcher.y = btnPause.y;
        screenSwitcher.addEventListener(egret.Event.CHANGE,this.setFullScreen,this);
        this.addChild(screenSwitcher);
        
        var position: eui.Label = new eui.Label();
        position.x = btnPlay.x;
        position.y = volume.y + volume.height + 20;
        this.addChild(position);
        position.addEventListener(egret.Event.ENTER_FRAME,this.showPosition,this);

        var btnPrintScreen: eui.Button = new eui.Button();
        btnPrintScreen.label = "截圖";
        btnPrintScreen.x = screenSwitcher.x + screenSwitcher.width + 40;
        btnPrintScreen.y = btnPlay.y;
        this.addChild(btnPrintScreen);
        btnPrintScreen.addEventListener(egret.TouchEvent.TOUCH_TAP,this.printScreen,this);       
    }
    private onLoadErr(e:egret.Event)
    { 
        console.log("video load error happend");
    }
    public play(e: egret.TouchEvent)
    {  //play(startTime:number,loop:boolean)播放該視訊
        this.video.play();
    }
    public pause(e: egret.TouchEvent)
    { //pause():void 暫停播放
        this.video.pause();
    }
    public setVoluem(e: egret.TouchEvent)
    { //volume:number 音量範圍從0(靜音)到1(最大音量)
        this.video.volume = e.target.value / 100;
    }
    public setFullScreen(e: egret.Event)
    { //fullscreen:boolean 是否全屏播放這個視訊(預設值true)
        this.video.fullscreen = e.target.selected;
        
    }
    public showPosition(e: egret.Event)
    { //position:number 當播放視訊時,position屬性表示視訊檔案中目前播放的位置(以妙為機關)
        e.target.text = "播放時間:" + this.video.position;
    }
    public printScreen(e: egret.Event) { 
        //Video中屬性 bitmapData:egret.BitmapData 擷取視訊的bitmapData,可以将視訊繪制到舞台上
        //BitmapData對象是一個包含像素資料的數組。
        var bitmapData: egret.BitmapData = this.video.bitmapData;
        bitmapData = this.video.bitmapData;
        //Bitmap類表示用于顯示位圖圖檔的顯示對象。bitmapData:egret.BitmapData 被引用的BitmapData對象
        var bitmap: egret.Bitmap = new egret.Bitmap();
        bitmap.bitmapData = bitmapData;
        bitmap.x = this.video.x;
        bitmap.y = this.video.y + this.video.height + 150;
        this.addChild(bitmap);
        console.log(bitmapData);
    }
}      

View Code

Egret官方案例學習筆記