首先,先了解一下什么是模态对话框,百度百科的给出了下面一个定义:

模态对话框(Modal Dialogue Box,又叫做模式对话框),是指在用户想要对对话框以外的应用程序进行操作时,必须首先对该对话框进行响应。如单击【确定】或【取消】按钮等将该对话框关闭。

游戏中经常会出现很多模态对话框,例如登陆框、提示框等等。

下面来看下效果图:

Cocos2d-js3.3 模态对话框的实现-LMLPHP

有几点值得关注的:

1.当对话框出现后,对话框外不响应触摸。

这就需要用到setSwallowTouches(),设置为true时,并且onTouchBegan返回true,就会吞没事件,不再向下传递

2.当对话框出现后,背景变暗

这里用到LayerColor的两个方法,设置颜色setColor()和设置透明度setOpacity()

下面,请看代码:

  1. var ModalDialogueBox = cc.LayerColor.extend({
  2. _listener: null,
  3. ctor: function() {
  4. this._super(cc.color.BLACK);
  5. this.ignoreAnchorPointForPosition(false);   //忽略锚点设置为false,默认为true,锚点(0, 0)
  6. this.setOpacity(128);       //透明度
  7. //初始化对话框
  8. this._initDialog();
  9. return true;
  10. },
  11. onEnter: function()
  12. {
  13. this._super();
  14. //监听器
  15. this._listener = new cc.EventListener.create({
  16. event: cc.EventListener.TOUCH_ONE_BY_ONE,
  17. swallowTouches: false,
  18. onTouchBegan: function(touch, event)
  19. {
  20. return true;
  21. }
  22. });
  23. //添加触摸监听
  24. cc.eventManager.addListener(this._listener, this);
  25. },
  26. //初始化对话框
  27. _initDialog: function()
  28. {
  29. var winSize = cc.winSize;
  30. //背景
  31. var bg = new cc.Sprite(res.dialog_png);
  32. bg.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
  33. this.addChild(bg, 0, 101);
  34. //OK按钮
  35. var OKLabel = new cc.LabelTTF("OK", "Arial", 36);
  36. var OKMenuItem = new cc.MenuItemLabel(OKLabel, this._onCallback, this);
  37. OKMenuItem.setPosition(cc.p(100, 50));
  38. //Cancel按钮
  39. var cancelLabel = new cc.LabelTTF("Cancel", "Arial", 36);
  40. var cancelMenuItem = new cc.MenuItemLabel(cancelLabel, this._onCallback, this);
  41. cancelMenuItem.setPosition(cc.p(250, 50));
  42. //菜单
  43. var menu = new cc.Menu(OKMenuItem, cancelMenuItem);
  44. menu.setPosition(cc.p(0, 0));
  45. bg.addChild(menu);      //注意是添加到背景里面
  46. this.setVisible(false);     //默认设置为不可见
  47. },
  48. _onCallback: function()
  49. {
  50. this.hidden();
  51. },
  52. //弹出
  53. popup: function()
  54. {
  55. this.setVisible(true);
  56. this._listener.setSwallowTouches(true);
  57. var bg = this.getChildByTag(101);
  58. bg.setScale(0);
  59. var scaleTo = new cc.ScaleTo(2.0, 1);
  60. var rotateBy = new cc.RotateBy(2.0, 360, 0);
  61. var spawn = new cc.Spawn(scaleTo, rotateBy);
  62. bg.runAction(spawn);
  63. },
  64. //隐藏
  65. hidden: function()
  66. {
  67. this.setVisible(false);
  68. this._listener.setSwallowTouches(false);
  69. },
  70. onExit: function()
  71. {
  72. this._super();
  73. //移除触摸监听
  74. cc.eventManager.removeListeners(cc.EventListener.TOUCH_ONE_BY_ONE, true);
  75. }
  76. });

源码下载:点击打开链接

05-07 14:53
查看更多