当前位置:  首页>> 技术小册>> cocos游戏开发入门

在 PlayerController 里面添加一个属性用于记录角色当前为多少步:

private _curMoveIndex: number = 0;
在 reset 方法中重置这个属性:

  1. reset() {
  2. this._curMoveIndex = 0;
  3. }

在 jumpByStep 中将这个步数增加,每次的增量是输入的步数:

  1. jumpByStep(step: number) {
  2. if (this._startJump) {
  3. return;
  4. }
  5. this._startJump = true;
  6. this._jumpStep = step;
  7. this._curJumpTime = 0;
  8. this._curJumpSpeed = this._jumpStep * BLOCK_SIZE/ this._jumpTime;
  9. this.getPosition(this._curPos);
  10. Vec3.add(this._targetPos, this._curPos, new Vec3(this._jumpStep* BLOCK_SIZE, 0, 0));
  11. if (this.BodyAnim) {
  12. if (step === 1) {
  13. this.BodyAnim.play('oneStep');
  14. } else if (step === 2) {
  15. this.BodyAnim.play('twoStep');
  16. }
  17. }
  18. this._curMoveIndex += step;
  19. }

在 PlayerController 中添加一个监听跳跃结束的方法:

  1. onOnceJumpEnd() {
  2. this.node.emit('JumpEnd', this._curMoveIndex);
  3. }

该方法派发了一个名为 JumpEnd 的事件,并将 _curMoveIndex 作为参数传递出去。

并在 PlayerController 的 update 方法中调用:

  1. update (deltaTime: number) {
  2. if (this._startJump) {
  3. this._curJumpTime += deltaTime;
  4. if (this._curJumpTime > this._jumpTime) {
  5. // end
  6. this.node.setPosition(this._targetPos);
  7. this._startJump = false;
  8. this.onOnceJumpEnd();
  9. } else {
  10. // tween
  11. this.node.getPosition(this._curPos);
  12. this._deltaPos.x = this._curJumpSpeed * deltaTime;
  13. Vec3.add(this._curPos, this._curPos, this._deltaPos);
  14. this.node.setPosition(this._curPos);
  15. }
  16. }
  17. }

回到 GameManager 并增加以下的处理:

增加一个 onPlayerJumpEnd 的方法

  1. onPlayerJumpEnd(moveIndex: number) {
  2. }

在 start 中监听 `` 的事件:

  1. start() {
  2. this.setCurState(GameState.GS_INIT);
  3. this.playerCtrl?.node.on('JumpEnd', this.onPlayerJumpEnd, this);
  4. }

可以看到这里我们使用的 this.playerCtrl?.node 也就是 PlayerController 的节点来接收事件,在 Cocos Creator 中,某个节点派发的事件,只能用这个节点的引用去监听。

增加一个用于判定角色是否跳跃到坑或者跳完所有地块的方法:

  1. checkResult(moveIndex: number) {
  2. if (moveIndex < this.roadLength) {
  3. if (this._road[moveIndex] == BlockType.BT_NONE) { //跳到了空方块上
  4. this.setCurState(GameState.GS_INIT)
  5. }
  6. } else { // 跳过了最大长度
  7. this.setCurState(GameState.GS_INIT);
  8. }
  9. }

填充 onPlayerJumpEnd 如下:

  1. onPlayerJumpEnd(moveIndex: number) {
  2. if (this.stepsLabel) {
  3. this.stepsLabel.string = '' + (moveIndex >= this.roadLength ? this.roadLength : moveIndex);
  4. }
  5. this.checkResult(moveIndex);
  6. }

上述的方法更新的计步器并检查角色是调到坑里面还是跳所有的方块,如果满足这两个条件,则重置整个游戏逻辑。


该分类下的相关小册推荐:

暂无相关推荐.