用了几天Egret现在对比一下Cocos Creator和 Egret场景创建时的些许不同,
1:Cocos Creator创建场景是直接在scene目录右键就可以创建一个场景十分简单,如果在其上面添加UI元素的时候直接新建节点,拖拽节点就行了,但是Egret就不同了,需要一系列的文件,新建exml文件在其上编辑,然后创建一个类来对应该exml文件类似安卓开发中的 xml文件对应一个Java文件
下面介绍一下Egret创建一个场景文件
一:创建一个Scene类,用于在UILayer上面添加节点
abstract class Scene extends eui.Component{
public constructor() {
super();
this.addEventListener(eui.UIEvent.COMPLETE,this.onComplete,this);
}
protected abstract onComplete();
}
二:创建一个场景管理类SceneManager该类是一个单例对象负责管理所有的场景对象
class SceneManager {
private static _manager: SceneManager = null;
public rootScene: eui.UILayer;
public firstScene: Scene;
public currentScene: Scene;
public static getInstance(): SceneManager {
if(this._manager === null) {
this._manager = new SceneManager();
}
return this._manager;
}
public goScene(s: Scene) {
// this.rootScene
if(this.currentScene) {
this.rootScene.removeChild(this.currentScene);
this.currentScene = null;
}
this.rootScene.addChild(s);
this.currentScene = s;
}
}
三:在文件中添加exml文件,首先添加第一个场景的exml文件
文件结构如下图所示:
编辑exml文件的时候如果打开它的时候 没有出现编辑该UI的视图工具,那么可以直接修改exml文件
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="firstSkin" width="750" height="1334" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing">
<e:Group>
<e:Rect id="back" width="750" height="1334" fillColor="0xdd2a2a" fillAlpha="0.5" strokeColor="0x424242" enabled="true">
</e:Rect>
<e:Label id="topLabel" width="750" height="200" text="第一个场景" verticalAlign="middle" italic="true" textAlign="center" size="50">
</e:Label>
</e:Group>
</e:Skin>
四:添加firstSkin.exml文件对应的ts文件
class FirstScene extends Scene{
private group: eui.Group;
public constructor() {
super();
this.skinName = "resource/game/firstSkin.exml";
console.log("group is ",this.group);
}
public onComplete() {
egret.log("第一个场景加载完成");
}
}
五:在游戏主逻辑中Main.ts添加场景代码:
protected createGameScene(): void {
// 得到场景管理器
let sceneManager = SceneManager.getInstance();
// 设置场景管理器的根节点为当前场景
sceneManager.rootScene = this;
let firstScene = new FirstScene();
sceneManager.goScene(firstScene);
}
六:运行程序:恭喜看到自己的第一个Egret场景了