cocos / cocos-docs

Manual docs content for Cocos Creator
https://docs.cocos.com
307 stars 462 forks source link

快速上手:制作第一个 2D 游戏 #2787

Closed SKY-KYJ closed 1 year ago

SKY-KYJ commented 1 year ago

URL : https://github.com/cocos-creator/creator-docs/blob/master/zh/getting-started/first-game-2d/index.md

根据手册的步骤执行,但实际展示的时候只会往上跳,并没有触发水平位移,把播放代码屏蔽后又能正常水平位移,最新3.8 版本,麻烦看看是什么问题

本地代码如下: import {_decorator, Component, Node, input, Input, EventMouse, Vec3, Animation} from 'cc';

const { ccclass, property } = _decorator;

export const BLOCK_SIZE = 40; // 添加一个放大比

@ccclass('PlayerController') export class PlayerController extends Component {

private _startJump: boolean = false; // 是否开始跳跃 private _jumpStep: number = 0; // 跳跃步数 private _curJumpTime: number = 0; // 跳跃时间 private _jumpTime: number = 0.1; // 当前的跳跃时间 private _curJumpSpeed: number = 0; // 移动速度 private _curPos: Vec3 = new Vec3(); // 当前的位置 private _deltaPos: Vec3 = new Vec3(0, 0, 0); // 位移 private _targetPos: Vec3 = new Vec3(); // 目标位置

@property(Animation) BodyAnim: Animation = null;

start() { input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this); }

update(deltaTime: number) { if (this._startJump) { this._curJumpTime += deltaTime; // 累计总的跳跃时间 if (this._curJumpTime > this._jumpTime) { // 当跳跃时间是否结束 // end this.node.setPosition(this._targetPos); // 强制位置到终点 this._startJump = false; // 清理跳跃标记 } 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); // 将位移设置给角色 } } }

onMouseUp(event: EventMouse) { if (event.getButton() === 0) { this.jumpByStep(1); } else if (event.getButton() === 2) { this.jumpByStep(2); } }

jumpByStep(step: number) { if (this._startJump) { return; } this._startJump = true; // 标记开始跳跃 this._jumpStep = step; // 跳跃的步数 1 或者 2 this._curJumpTime = 0; // 重置开始跳跃的时间

const clipName = step == 1 ? 'oneStep' : 'twoStep';
const state = this.BodyAnim.getState(clipName);
this._jumpTime = state.duration;

this._curJumpSpeed = this._jumpStep * BLOCK_SIZE / this._jumpTime; // 根据时间计算出速度
this.node.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');
  }
}

}

}

SKY-KYJ commented 1 year ago

已知问题点了,因为层级不是太明晰的说明是在player 层,导致一直以为是在body层,而且还能继续写下去能操作交互,导致后面一直无法定位问题所在,建议在后面跳跃处备注一下注意事项,否则很多人会遗漏的