天天看點

用CocosCreator來做一個黃金礦工吧(二)

繩子的拉長與縮短

從Atlas檔案夾找到這2個鈎子的圖檔,

按照圖檔擺放

左邊鈎子的錨點anchor設定為1,1,左右鈎子的錨點設定為0,1,這裡目前沒有做動畫,後期如果加上了鈎子旋轉動畫,錨點設定好了,旋轉中心才正确

因為接下來要用代碼延長繩子的長度,我們直接在屬性面闆調整繩子的高度(Size.H)

用CocosCreator來做一個黃金礦工吧(二)

發現鈎子沒有跟着繩子動,怎麼辦呢?

這時萬能的Wiget元件又來了,為鈎子添加Widget元件,并設定,數值可以自己調,比如我的就是

用CocosCreator來做一個黃金礦工吧(二)

再次修改Hook的高度,發現,已經達到我們想要的效果了

用CocosCreator來做一個黃金礦工吧(二)

接下來就編寫伸長縮短代碼了

是時候上代碼了

在class外面定義好常量

Hook.ts

const { ccclass, property } = cc._decorator;

let ROPE_STATE = cc.Enum({
    ADD: 1, //增加
    REDUCE: 2, //減少
    WAIT: 3 //等待
});
           

class内建立屬性

ropeSpeed :number = 100; //繩子長度變化速度
ropeOriginalHeight: number; //繩子初始長度
           

編寫繩子長度改變代碼

start裡擷取繩子初始長度,指派初始狀态

start() {
    this.ropeState = ROPE_STATE.WAIT;
    this.ropeOriginalHeight = this.node.height;
}
           
/**
 * 繩子長度改變 
 */
hookLengthen(deltaTime) {
    //變長時
    if (this.ropeState == ROPE_STATE.ADD) {
        this.node.height += 100 * deltaTime;
    } else if (this.ropeState == ROPE_STATE.REDUCE) {
        //縮短時
        this.node.height -= this.ropeSpeed * deltaTime;
        //當長度小于等于于初始長度
        if (this.node.height <= this.ropeOriginalHeight) {
            //繩子重新開始旋轉
            this.isRotating = true;
            //重置各種屬性
            this.ropeState = ROPE_STATE.WAIT;
            this.node.height = this.ropeOriginalHeight;
            this.node.angle = 0;
            this.rotateSpeed = 100;
        }
    }
}
           

同樣放進update裡

update(deltaTime) {
    this.rotateHook(deltaTime)
    this.hookLengthen(deltaTime);
}
           

添加螢幕觸碰事件控制繩子狀态

首先class裡定義一個屬性

@property(cc.Node)
canvas: cc.Node;
           

點開Hook的屬性面闆,将左側canvas拖進去,這樣點選整個螢幕,都可以接受到觸摸事件

this.canvas.on(cc.Node.EventType.TOUCH_END,this.sendHook.bind(this));
           
/**
 * 發射鈎子
 */
sendHook() {
    this.isRotating = false;
    // 繩子變長中點選,繩子切換到變短狀态
    if (this.ropeState == ROPE_STATE.ADD) {
        this.ropeState = ROPE_STATE.REDUCE;
    }
    // 繩子等待中點選,繩子切換到變長狀态
    if (this.ropeState == ROPE_STATE.WAIT) {
        this.ropeState = ROPE_STATE.ADD;
    }
}
           

運作遊戲,試試看吧

用CocosCreator來做一個黃金礦工吧(二)

繼續閱讀