• Egret官方案例学习笔记


    1.资源记载方式

    (1)Egret引擎是2.0.5。

    (2)resource/resource.json文件是:

    {
        "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类

    /**
     *
     * @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类 

    /**
     *
     * @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我是光头强
     你是大熊";//用
    来换行
            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文件是:

    {
        "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类

    /**
    *
    * @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文件是:

    {
        "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类

    /**
    *
    * @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 += "
    " + event.stageX + "," + event.stageY;
            msg += "
    " + event.localX+ "," + event.localY;
            msg += "
    " + event.currentTarget.name + "," + event.target.name;
            alert(msg);
           
                  
            }
            
            }
    View Code

    5.进度条的加载

    (1)Egret引擎是2.05

    (2)resource/assets中根据resource/resource.json文件配置相关资源。resource/resource.json文件是:

    {
        "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

    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

    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实现了本地存储的功能。存储数据需要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”

    {
        "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配置。

    {
    "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)到了这一步骤,配置工作都完成了,下面就是代码的运用了。
    当然首先是加载资源了。

    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)

    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)

        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)结果

    打印:

    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)

      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

    /*
    * 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

    /**
     * 播放器的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

    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

    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

    /**
     *
     * @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


     

  • 相关阅读:
    jstack使用-倒出线程堆栈
    sentos nginx安装
    阿里云主机添加云磁盘
    redis 安装并设置为开机启动服务
    curl命令使用小结[转]
    FormView控件下DropDownList是否可以绑定
    数据绑定之DataFormatString
    GridView控件RowDataBound事件中获取列字段值的几种途径 !!!
    怎么用SQL语句备份和恢复数据库?
    XtraReports 入门教程
  • 原文地址:https://www.cnblogs.com/heisaijuzhen/p/4894879.html
Copyright © 2020-2023  润新知