1. 程式人生 > >CocosCreator之KUOKUO帶你利用物件池實現cc.graphics的單步撤銷

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~~