这个游戏效果大概是这样的:
点击调色盘,即可给音符上色。
听起来简单,做起来还是有几个难点的。
1. 拖拽画笔并且确定画笔点击的颜色;
2.切换画笔到对应的颜色;
3.确定选择的是哪个音符;
4.涂上对应的颜色;
1、创建界面
a. 使用的是EXML可视化编辑器,用这个的话,页面布局用手拖动就可以了,不必再用ts计算。官方文档http://developer.egret.com/cn/github/egret-docs/Wing/exmlEditor/index.html 也可以查看我的另外一篇博客https://www.cnblogs.com/caoshufang/p/12074230.html
编写界面的时候不要偷懒记得给它们加上name属性,这个name属性在后面有大作用。添加的话点击所有属性里就可以找到啦。
b. 把创建好了的界面添加到舞台上。
1 /**
2 * 创建场景界面
3 * Create scene interface
4 */
5 protected createGameScene(): void {
6 const coloringScene = new ColoringScene();
7 coloringScene.skinName = `resource/eui_skins/ColoringScene.exml`;
8 coloringScene.x = 0;
9 coloringScene.y = 0;
10 this.addChild(coloringScene);
11 }
2、拖拽画笔:
拖拽这个行为可以参考官方的https://developer.egret.com/cn/article/index/id/583
3、确定点击的是调色板里的哪个颜色
因为是使用EXML编辑器,所有的eui组件在页面里按照ID声明好了以后就能用了。
1 // 调色盘颜色数组
2 const colorArr: Array<eui.Image> = [this.orangeColor, this.greenColor, this.brownColor, this.yellowColor, this.redColor, this.violetColor];
3 this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE, onMove, this);
4
5 // 给每个颜色都加上点对象碰撞检测、创建对应颜色的画笔
6 colorArr.map((item, index) => {
7 this.isHitColor = item.hitTestPoint(target.x, target.y);
8
9 if (this.isHitColor) {
10 this.selectColor = item.name.charAt(0).toUpperCase() + item.name.slice(1);
11 const penRes: string = 'pen' + this.selectColor + '_png';
12 draggedObject.source = penRes;
13 }
14 })
hitTestPoint()是egret自带的方法,具体自己去看官方文档
这里其实就是在鼠标拖拽停止事件里把颜色数组里的每一项都注册与画笔笔尖的碰撞检测,如果碰撞了之后就替换画笔的资源。
这里其实还有另外一种做法就是不替换画笔的资源而是重新创建一个新的画笔,把原来画笔的属性都赋值给它

就是我下面注释了的代码。这种做法不是很好,因为一句代码能解决的事为什么要写这么长。而且这还没写完,还要把拖拽事件给转移到新的画笔身上。十分不友好,建议直接替换资源省事。
4.涂上对应的颜色
确定了点击的是哪个颜色之后还要给音符上色,做法与之前类似,也是创建个音符数组,检测音符对象与画笔笔尖这个点的碰撞。
1 // 音符数组
2 const noteArr: Array<eui.Image> = [this.noteLeftTop, this.noteRightTop, this.noteLeftBottom, this.noteRightBottom];
3
4 // 给每个音符都加上点对象碰撞检测、创建对应颜色的音符 noteGreen_png noteWhite_png
5 noteArr.map((item, index) => {
6 this.isHitNote = item.hitTestPoint(target.x, target.y);
7
8 if (this.isHitNote) {
9 const noteRes: string = 'note' + this.selectColor + '_png';
10 item.source = noteRes;
11 }
12 })
5、重置游戏
使用egret内部API
1 this.removeChildren();
2 this.createGameScene();
核心的代码和思路就是这些啦
总结:
其实做游戏要求逻辑性强一些,我之前做的都是网站,刚开始做这个就有个不好的习惯,就是边想边做,这样其实很不好,因为做错了又要改,改来改去思路都乱了,还不如在一开始就把思路先在纸上写清楚,再分成小点,按部就班。
来源:oschina
链接:https://my.oschina.net/u/4356644/blog/4289662