用CocosCreator来做一个黄金矿工吧(二)

绳子的拉长与缩短

从Atlas文件夹找到这2个钩子的图片,
按照图片摆放
image.png

是时候上代码了

在class外面定义好常量

Hook.ts

const { ccclass, property } = cc._decorator;

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


@ccclass
export class Hook extends ...

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拖进去,这样点击整个屏幕,都可以接受到触摸事件
image.png
start里添加代码

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;
    }
}

运行游戏,试试看吧
GIF3.gif

你可能感兴趣的:(cocos,游戏开发,typescript)