绳子的拉长与缩短
从Atlas文件夹找到这2个钩子的图片,
按照图片摆放
左边钩子的锚点anchor设置为1,1,左右钩子的锚点设置为0,1,这里目前没有做动画,后期如果加上了钩子旋转动画,锚点设置好了,旋转中心才正确
因为接下来要用代码延长绳子的长度,我们直接在属性面板调整绳子的高度(Size.H)
发现钩子没有跟着绳子动,怎么办呢
这时万能的Wiget组件又来了,为钩子添加Widget组件,并设置,数值可以自己调
再次修改Hook的高度,发现,已经达到我们想要的效果了
是时候上代码了
在class外面定义好常量
Hook.ts
const { ccclass, property } = cc._decorator;let ROPE_STATE = cc.Enum({ ADD: 1, //增加 REDUCE: 2, //减少 WAIT: 3 //等待});@ccclassexport 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拖进去,这样点击整个屏幕,都可以接受到触摸事件
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; }}
运行游戏,试试看吧