提问人:Cbubg 提问时间:11/14/2023 更新时间:11/15/2023 访问量:43
为什么 Cocos creator 3.8 tween 不能进入异步 func(使用 Promise)
Why Cocos creator 3.8 tween doesnt work into async func (with Promise)
问:
我是 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;
}
但它不起作用。
经过一些测试,我调查了一下:
- 如果 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'))
}
我在节点移动后获得已完成的日志。
- 我的异步函数中的 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 的信息很少,所以我真的需要帮助。
答:
0赞
Cbubg
11/15/2023
#1
好的,在另一个类中出现了一个问题,我在同一时刻调用了 Tween.Stop() func。这个功能停止了现场所有活跃的补间,所以我的补间在启动后不知不觉地停止了。Promises没有问题!
评论
0赞
Mr. Nun.
11/15/2023
嘿,我已经看过你的答案和问题,在我看来,它与社区并不那么相关。恕我直言,您可能应该删除它。继续编码:)
0赞
OscarLeif
11/19/2023
嗯,这实际上是很好的信息。
评论