正文
在Cocos Creator游戏开发中,经常需要使用到弹出式对话框,下面我们就一起来封装下自己的弹出式对话框。
一、弹出式对话框原理解析
1:对话框的结构:
1. `根节点 -->`
2. `mask: 全屏的单色精灵,监听事件,关闭对话框;`
3. `dlg 与它的孩子: 对话框的内容,监听事件,挡住不让他传递到mask节点上;`
4. `弹出时动画:`
5. `mask: 渐变进来;`
6. `对话框内容缩放,并加上easing缓动对象;`
7. `收起时动画:`
8. `mask: 渐变出去;`
9. `对话框内容缩小,并加上easing 缓动对象;`
2: 对话框组件脚本
1. `(1)show_dlg`
2. `(2)hide_dlg`
二、弹出式对话框控制组件
1. `const {ccclass, property} = cc._decorator;`
3. `@ccclass`
4. `export default class PopDialogCtrl extends cc.Component {`
5. ` @property({type:cc.Node, tooltip:"弹出式对话框的遮罩节点"})`
6. ` mask : cc.Node = null;`
7. ` @property({type:cc.Node, tooltip:"弹出式对话框的主体内容节点"})`
8. ` content : cc.Node = null;`
9. ` @property({tooltip:"弹出式对话框初始化时的透明度"})`
10. `maskOpacity : number = 200;`
12. ` onLoad(){`
13. ` this.node.active = false;`
14. ` this.mask.opacity = this.maskOpacity;`
15. `}`
17. ` showDialog(){`
18. ` this.node.active = true;`
19. ` // mask淡入`
20. ` this.mask.opacity = 0;`
21. ` let fIn : cc.Action = cc.fadeTo(0.1, this.maskOpacity);`
22. ` this.mask.runAction(fIn);`
24. ` // content缩放显示`
25. ` this.content.setScale(0, 0);`
26. ` let s : cc.Action = cc.scaleTo(0.2, 1, 1).easing(cc.easeBackOut());`
27. ` this.content.runAction(s);`
28. ` }`
29. ` hideDialog(){`
30. ` // mask淡出`
31. ` this.mask.opacity = 0;`
32. ` let fOut : cc.Action = cc.fadeTo(0.3, 0);`
33. ` this.mask.runAction(fOut);`
34. ` // content缩放隐藏`
35. ` let s : cc.Action = cc.scaleTo(0.4, 0, 0).easing(cc.easeBackIn());`
36. ` let endf : cc.Action = cc.callFunc(function(){`
37. ` this.node.active = false;`
38. ` }.bind(this));`
39. ` let seq : cc.ActionInterval = cc.sequence([s, endf]);`
40. ` this.content.runAction(seq);`
41. ` }`
42. `}`
三、弹出式对话框UI制作
上面设置,可以保证点击遮罩层的时候隐藏对话框。
四、弹出式对话框组件的使用
新建GameMgr.ts挂载到Canvas节点上
1. `import PopDialogCtrl from "./PopDialogCtrl";`
3. `const {ccclass, property} = cc._decorator;`
4. `@ccclass`
5. `export default class GameMgrextends cc.Component { `
6. ` @property({type:PopDialogCtrl, tooltip:"弹出式对话框"})`
7. ` popDialog : PopDialogCtrl = null;`
8. ` showDialog(){`
9. ` this.popDialog.showDialog();`
10. ` }`
11. `}`