在 PlayerController 里面添加一个属性用于记录角色当前为多少步:
private _curMoveIndex: number = 0;
在 reset 方法中重置这个属性:
reset() {
this._curMoveIndex = 0;
}
在 jumpByStep 中将这个步数增加,每次的增量是输入的步数:
jumpByStep(step: number) {
if (this._startJump) {
return;
}
this._startJump = true;
this._jumpStep = step;
this._curJumpTime = 0;
this._curJumpSpeed = this._jumpStep * BLOCK_SIZE/ this._jumpTime;
this.getPosition(this._curPos);
Vec3.add(this._targetPos, this._curPos, new Vec3(this._jumpStep* BLOCK_SIZE, 0, 0));
if (this.BodyAnim) {
if (step === 1) {
this.BodyAnim.play('oneStep');
} else if (step === 2) {
this.BodyAnim.play('twoStep');
}
}
this._curMoveIndex += step;
}
在 PlayerController 中添加一个监听跳跃结束的方法:
onOnceJumpEnd() {
this.node.emit('JumpEnd', this._curMoveIndex);
}
该方法派发了一个名为 JumpEnd 的事件,并将 _curMoveIndex 作为参数传递出去。
并在 PlayerController 的 update 方法中调用:
update (deltaTime: number) {
if (this._startJump) {
this._curJumpTime += deltaTime;
if (this._curJumpTime > this._jumpTime) {
// end
this.node.setPosition(this._targetPos);
this._startJump = false;
this.onOnceJumpEnd();
} else {
// tween
this.node.getPosition(this._curPos);
this._deltaPos.x = this._curJumpSpeed * deltaTime;
Vec3.add(this._curPos, this._curPos, this._deltaPos);
this.node.setPosition(this._curPos);
}
}
}
回到 GameManager 并增加以下的处理:
增加一个 onPlayerJumpEnd 的方法
onPlayerJumpEnd(moveIndex: number) {
}
在 start 中监听 `` 的事件:
start() {
this.setCurState(GameState.GS_INIT);
this.playerCtrl?.node.on('JumpEnd', this.onPlayerJumpEnd, this);
}
可以看到这里我们使用的 this.playerCtrl?.node 也就是 PlayerController 的节点来接收事件,在 Cocos Creator 中,某个节点派发的事件,只能用这个节点的引用去监听。
增加一个用于判定角色是否跳跃到坑或者跳完所有地块的方法:
checkResult(moveIndex: number) {
if (moveIndex < this.roadLength) {
if (this._road[moveIndex] == BlockType.BT_NONE) { //跳到了空方块上
this.setCurState(GameState.GS_INIT)
}
} else { // 跳过了最大长度
this.setCurState(GameState.GS_INIT);
}
}
填充 onPlayerJumpEnd 如下:
onPlayerJumpEnd(moveIndex: number) {
if (this.stepsLabel) {
this.stepsLabel.string = '' + (moveIndex >= this.roadLength ? this.roadLength : moveIndex);
}
this.checkResult(moveIndex);
}
上述的方法更新的计步器并检查角色是调到坑里面还是跳所有的方块,如果满足这两个条件,则重置整个游戏逻辑。
暂无相关推荐.