Use CocosCreator to be a gold miner (2)

Posted May 28, 20202 min read

Elongation and shortening of rope

Find the pictures of these 2 hooks from the Atlas folder,
According to the picture
The anchor of the left hook is set to 1,1, and the anchor of the left and right hooks is set to 0,1. There is no animation here. If the hook rotation animation is added later, the anchor point is set and the center of rotation is correct.
Because the next step is to use the code to extend the length of the rope, we directly adjust the height of the rope in the property panel(Size.H)
I found that the hook didn't follow the rope, what should I do?
At this time, the omnipotent Wiget component is here again. Add the Widget component to the hook and set it. The value can be adjusted by yourself.
Modify the height of Hook again, and found that we have achieved the desired effect

It's time to code

Define constants outside the class


const {ccclass, property} = cc._decorator;

let ROPE_STATE = cc.Enum({
    ADD:1, //increase
    REDUCE:2, //decrease
    WAIT:3 //wait

export class Hook extends ...

New attribute in class

ropeSpeed:number = 100; //Speed   of rope length change
ropeOriginalHeight:number; //The initial length of the rope

Write code to change rope length

Get the initial length of the rope in start and assign the initial state

start() {
    this.ropeState = ROPE_STATE.WAIT;
    this.ropeOriginalHeight = this.node.height;

* The length of the rope changes
* /
hookLengthen(deltaTime) {
//When it becomes longer
if(this.ropeState == ROPE_STATE.ADD) {
this.node.height + = 100 * deltaTime;
} else if(this.ropeState == ROPE_STATE.REDUCE) {
//When shortened
this.node.height-= this.ropeSpeed * deltaTime;
//When the length is less than or equal to the initial length
if(this.node.height <= this.ropeOriginalHeight) {
//The rope starts to spin again
this.isRotating = true;
//Reset various attributes
this.ropeState = ROPE_STATE.WAIT;
this.node.height = this.ropeOriginalHeight;
this.node.angle = 0;
this.rotateSpeed = 100;

Also put in update

update(deltaTime) {

Add screen touch event to control rope status

First define an attribute in the class


Click on the Hook property panel and drag the canvas on the left, so that you can receive touch events by clicking on the entire screen
Add code to start

this.canvas.on(cc.Node.EventType.TOUCH_END, this.sendHook.bind(this));

* Launch hook
* /
sendHook() {
this.isRotating = false;
//Click on the rope to become longer, the rope will switch to the shorter state
if(this.ropeState == ROPE_STATE.ADD) {
this.ropeState = ROPE_STATE.REDUCE;
//Click while the rope is waiting, and the rope switches to a variable length state
if(this.ropeState == ROPE_STATE.WAIT) {
this.ropeState = ROPE_STATE.ADD;

Run the game, give it a try