@Component
export default class JumpAnim extends Script {

    /**跳跃动画的Guid */
    @Property({ displayName: "跳跃动画Guid" })
    jumpAnimGuid = "150691"


    /**角色 */
    char: Character
    /**跳跃动画 */
    jumpAnim: Animation


    /**角色进入Jumping状态前的Z轴数值（通过高度差，判断此时是跳跃还是掉落） */
    lastLocZ: number
    /**一次跳跃是否完成 */
    isJumpFinish: boolean = true
    /**生成器（用来分帧执行逻辑） */
    private _logicQueue: Generator<void, void, unknown>;



    protected async onStart(): Promise<void> {
        if (SystemUtil.isClient()) {
            // 下载并加载资源
            await AssetUtil.asyncDownloadAsset(this.jumpAnimGuid)
            // 获取玩家
            this.char = (await Player.asyncGetLocalPlayer()).character
            // 加载动画
            this.jumpAnim = this.char.loadAnimation(this.jumpAnimGuid)
            // 开启update
            this.useUpdate = true
        }
    }


    protected onUpdate(dt: number): void {
        // 如果生成器存在
        if (this._logicQueue) {
            // 执行生成器逻辑，并判断是否执行完成，执行完成关闭生成器
            if (this._logicQueue.next().done) {
                this._logicQueue = null;
            }
        }

        // 如果上次跳跃已经完成，检查角色是否进行下一次跳跃
        if (this.isJumpFinish) {
            // 如果角色正在跳跃
            if (this.char.isJumping) {
                // 记录起跳时的Z轴
                this.lastLocZ = this.char.worldTransform.position.z
                //将跳跃完成状态设置为未完成
                this.isJumpFinish = false
                // 开启生成器，判断下一帧的Z轴
                this._logicQueue = this.innerLogic();
            }
        } else {
            // 如果跳跃未完成，但是已经不属于Jumping状态了，证明此次跳跃结束
            if (!this.char.isJumping) {
                this.isJumpFinish = true
                this.jumpAnim.stop()
            }
        }
    }

    /**生成器（检查下一帧的Z轴，并进行跳跃） */
    private * innerLogic() {
        yield this.checkZandJump()
    }

    /**检查Z轴的变化以进行跳跃 */
    private checkZandJump() {
        // 如果当前帧Z轴比上一帧Z轴大，证明角色正在向上跳跃（因为下落状态也属于Jumping，所以需要这样判断）
        if (this.char.worldTransform.position.z > this.lastLocZ) {
            // 播放跳跃动画
            this.jumpAnim.play()
        }
    }
}