Cocos Creator弹出式对话框实现
在Cocos Creator游戏开发中,经常需要使用到弹出式对话框,下面我们就一起来封装下自己的弹出式对话框。
一、弹出式对话框原理解析
1:对话框的结构:
根节点 -->
mask: 全屏的单色精灵,监听事件,关闭对话框;
dlg 与它的孩子: 对话框的内容,监听事件,挡住不让他传递到mask节点上;
弹出时动画:
mask: 渐变进来;
对话框内容缩放,并加上easing缓动对象;
收起时动画:
mask: 渐变出去;
对话框内容缩小,并加上easing 缓动对象;
2: 对话框组件脚本
(1)show_dlg
(2)hide_dlg
二、弹出式对话框控制组件
const {ccclass, property} = cc._decorator;
@ccclass
export default class PopDialogCtrl extends cc.Component {
@property({type:cc.Node, tooltip:"弹出式对话框的遮罩节点"})
mask : cc.Node = null;
@property({type:cc.Node, tooltip:"弹出式对话框的主体内容节点"})
content : cc.Node = null;
@property({tooltip:"弹出式对话框初始化时的透明度"})
maskOpacity : number = 200;
onLoad(){
this.node.active = false;
this.mask.opacity = this.maskOpacity;
}
showDialog(){
this.node.active = true;
// mask淡入
this.mask.opacity = 0;
let fIn : cc.Action = cc.fadeTo(0.1, this.maskOpacity);
this.mask.runAction(fIn);
// content缩放显示
this.content.setScale(0, 0);
let s : cc.Action = cc.scaleTo(0.2, 1, 1).easing(cc.easeBackOut());
this.content.runAction(s);
}
hideDialog(){
// mask淡出
this.mask.opacity = 0;
let fOut : cc.Action = cc.fadeTo(0.3, 0);
this.mask.runAction(fOut);
// content缩放隐藏
let s : cc.Action = cc.scaleTo(0.4, 0, 0).easing(cc.easeBackIn());
let endf : cc.Action = cc.callFunc(function(){
this.node.active = false;
}.bind(this));
let seq : cc.ActionInterval = cc.sequence([s, endf]);
this.content.runAction(seq);
}
}
三、弹出式对话框UI制作

上面设置,可以保证点击遮罩层的时候隐藏对话框。
四、弹出式对话框组件的使用
新建GameMgr.ts挂载到Canvas节点上。
import PopDialogCtrl from "./PopDialogCtrl";
const {ccclass, property} = cc._decorator;
@ccclass
export default class GameMgr extends cc.Component {
@property({type:PopDialogCtrl, tooltip:"弹出式对话框"})
popDialog : PopDialogCtrl = null;
showDialog(){
this.popDialog.showDialog();
}
}


想要获取更多课程和知识请点击:
https://bycwedu.vipwan.cn/promotion_channels/630597732