为什么 Cocos creator 3.8 tween 不能进入异步 func(使用 Promise)

Why Cocos creator 3.8 tween doesnt work into async func (with Promise)

提问人:Cbubg 提问时间:11/14/2023 更新时间:11/15/2023 访问量:43

问:

我是 Cocos Creator 引擎的新手,现在完全坚持补间。

我的代码中有下一个补间功能:

    private magnetTween(pos: Vec3): Tween<Readonly<Vec3>>
    {
        const offset = Math.abs(this.node.worldPosition.x - pos.x);
        const duration = offset / this.gameConfig.CameraConfig.MagnetSpeed;
        console.log('tween duration ' + duration)

        return tween(this.node.worldPosition).to(duration, pos,
            {
                onUpdate: (target: Vec3) => 
                {
                    this.node.setWorldPosition(target);
                }
            });
    }

还有我真正需要在其他课程中等待的下一个承诺

    public async magnetTo(obj: Node): Promise<void>
    {
        console.log('magnet func start');

        const pos = obj.getWorldPosition();

        const prm = new Promise<void>((resolve, reject) => {
            this.magnetTween(pos)
             .call(() => resolve())
             .start();
        });

        await prm;
    }

但它不起作用。

经过一些测试,我调查了一下:

  1. 如果 Tween 是从异步函数中调用的,则它可以正常工作。如果我这样称呼它:
    protected start(): void 
    {
        const pos = new Vec3(10000, 0, 0);

        const promise = new Promise<void>((resolve, reject) => { this.magnetTween(pos)
             .call(() => resolve())
             .start();});

        promise.then(value => console.log('completed'))
    }

我在节点移动后获得已完成的日志。

  1. 我的异步函数中的 promise 也可以正常工作。如果我使用下面的语法,我也会在超时后获得完成的日志
    public async magnetTo(obj: Node): Promise<void>
    {
        console.log('magnet func start');

        this.delay = 1000;
        const prn = new Promise<number>((resolve, reject) => 
        {
           setTimeout(resolve, this.delay);
        });

        await prn;
        console.log('completed')
    }

网络上关于 Cocos 的信息很少,所以我真的需要帮助。

TypeScript Promise Tween CocosCreator

评论

0赞 Bergi 11/15/2023
"但它不起作用。- 究竟什么不起作用,发生了什么?我看不出你的代码有任何明显的缺陷,正如你所展示的,一般方法确实有效。
0赞 Cbubg 11/15/2023
在 Promise+Tween 代码的情况下,我的对象不会移动,功能也不会完成 - 只是永恒地等待着。我注意到补间onUpdate块在放入Promise时没有运行。但我怀疑这是正确的行为。

答:

0赞 Cbubg 11/15/2023 #1

好的,在另一个类中出现了一个问题,我在同一时刻调用了 Tween.Stop() func。这个功能停止了现场所有活跃的补间,所以我的补间在启动后不知不觉地停止了。Promises没有问题!

评论

0赞 Mr. Nun. 11/15/2023
嘿,我已经看过你的答案和问题,在我看来,它与社区并不那么相关。恕我直言,您可能应该删除它。继续编码:)
0赞 OscarLeif 11/19/2023
嗯,这实际上是很好的信息。