CocosCreator之KUOKUO带你利用对象池实现cc.graphics的单步撤销

本次引擎2.0.5

编辑工具VSCode

目标:画笔单步撤销。

方法:对象池存储节点,通过回收实现单步撤销。

新建工程:bk白色背景。

新建个空节点:drawManager(便于管理预制体)

然后新建一个空节点,绑上cc.graphics。做成预制体。

好了,让我们写总控制脚本main绑定在Canvas上。

声明节点和预制体:

写个对象池:

这样对象池里面就有200个提前预制好的带cc.graphics组件的节点。

写一个创造方法,然后在对象池下方先实例化50个;

都在onLoad

好了,节点有了,怎么找到这些节点呢??

我们可以声明一个下标:

好了,这样我们就可以通过children下标找寻节点。

因为我们有个drawManager专门做这个的:

好了,让我们写出3个触摸监听:

下标从0开始;

第一步开始固定点;

第二步开始不断画线;

第三步结束触摸,下标加一;

第四步判断下标是否越界,可以再添加节点。

好了,现在我们这样就可以使用下标单步撤销了。

建个按钮:

写个点击方法:

如果是一笔没画,return;

不然会清除该节点的绘画,回收到节点池;

然后下标减去1;

给出源代码:

cc.Class({
    extends: cc.Component,

    properties: {
        drawManager : cc.Node,
        // 预制
        draw : cc.Prefab,
        // 对应下标
        index : 0
    },

    onLoad () {
        // 对象池
        this.drawPool = new cc.NodePool();
        let initCount = 200;
        for (let i = 0; i < initCount; ++i) {
            let draw = cc.instantiate(this.draw);
            this.drawPool.put(draw);
        }
        // 先取出50个实例化
        for (let i = 0; i < 50; ++i) {
            this.createDraw();
        }
    },

    start () {
        this.draw_children = this.drawManager.children;
        // 触摸监听
        this.node.on('touchstart',function(touch) {
            var t_pos = touch.getLocation();
            var pos = this.node.convertToNodeSpaceAR(t_pos);
            this.draw_children[this.index].getComponent(cc.Graphics).moveTo(pos.x,pos.y);
        },this);

        this.node.on('touchmove',function(touch) {
            var t_pos = touch.getLocation();
            var pos = this.node.convertToNodeSpaceAR(t_pos);
            this.draw_children[this.index].getComponent(cc.Graphics).lineTo(pos.x,pos.y);
            this.draw_children[this.index].getComponent(cc.Graphics).stroke();
        },this);

        this.node.on('touchend',function(touch) {
            this.index += 1;
            if (this.index >= this.draw_children.length) {
                this.createDraw();
            }
        },this);
    },

    // 创造绘图节点并实例化
    createDraw() {
        let draw = null;
        if (this.drawPool.size() > 0) {
            draw = this.drawPool.get();
        }
        else {
            draw = cc.instantiate(this.draw);
        }
        draw.parent = this.drawManager;
    },

    Click_back() {
        if(this.index <= 0) {
            return;
        }
        this.draw_children[this.index - 1].getComponent(cc.Graphics).clear();
        this.drawPool.put(this.draw_children[this.index - 1]);
        this.index -= 1;
    },
});

好了,我们试一试;

怎么样?

小伙伴们有更好的方法吗?

O(∩_∩)O~~

猜你喜欢

转载自blog.csdn.net/kuokuo666/article/details/84867049