cocos新手引导的遮罩组件

首先先明确下需求,新手引导一般会屏蔽了除期望操作组件之外的所有ui的操作。也就是说,除了指定的组件,你不可以点击其他的组件。然后直接上代码吧:

cc.Class({
    extends: cc.Component,

    properties: {
        targetNodePath: ''
    },

    onLoad () {
        let touchListener = cc.EventListener.create({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches: true,
            owner: this.node,
            onTouchBegan: (touch, event)=>{
                const node = cc.find(this.targetNodePath);
                if(!(node && cc.isValid(node))){
                    console.warn("can't find node by path:", this.targetNodePath);
                    return false;
                }
                const box = node.getBoundingBoxToWorld();
                return !box.contains(touch.getLocation());
            }
        });
        cc.eventManager.addListener(touchListener, this.node);
    }

});

基本思路就是在最上层监听TOUCH_BEGAN事件,并且指定放行的组件路径(使用路径而不是节点是为了方便读取配置表),屏蔽除指定组件之外的ui。以上代码仅能在creator 1.x上运行,因为使用了eventManager,在2.x中将会被移除。目前项目使用1.9.3,计划升级1.10,因此暂无问题。 那么我们思考下在2.x中,这个接口被移除了,我们因该如何处理呢。我想了下,其实也很好解决。以下是我的思路(懒得写代码了):

  • 首先在最上层用一个Button或者BlockInputEvent组件遮蔽所有的用户输入
  • 然后指定放行的组件,在遮罩上方同位置创建一个等大小的button,执行对应组件的Component.EventHandler,至于缩放什么的表现可能需要自己手动弄个动画了,想来也是很方便的

猜你喜欢

转载自my.oschina.net/u/3905200/blog/1923528