我有以下 JavaScript 代码:
if (condition == 'true'){
this.function1();
this.function2();
}
function1() 代码:
function1(){
this.node.getChildByName("spriteName").active = true;
this.node.getChildByName("spriteName").runAction(cc.moveTo(0.1, x, y));
}
function2() 代码:
function2(){
this.node.getChildByName("spriteName").active = false;
}
如何确保只有在 function1 完成后才调用 function2?
我试过 cc.delayTime()
但它不合适。
答案 0 :(得分:1)
我假设您使用的是 Cocos Creator 2.4
。
操作系统目前已弃用 (source)。改用 cc.tween
可能是明智之举。
您可以使用 cc.tween
方法(例如 to
和 call
)来移动节点并调用方法。
这是使用您提供的代码(在 TypeScript 中)制作的示例。
const {ccclass, property} = cc._decorator;
@ccclass
export default class TestScript extends cc.Component
{
private x: number = 15;
private y: number = 15;
start()
{
this.function1();
}
function1()
{
const sprite = this.node.getChildByName("spriteName");
sprite.active = true;
cc.tween(sprite)
.to(1, { position: cc.v3(this.x, this.y, 0) })
.call(() => this.function2())
.start();
}
function2()
{
this.node.getChildByName("spriteName").active = false;
}
}
如果您仍希望保留最初的解决方案,您可以在操作完成后使用 cc.sequence
和 cc.callFunc
调用方法。第一个方法将用于依次调用动作,另一个方法将用作仅调用方法的动作。
这是使用您提供的代码(在 TypeScript 中)制作的另一个示例。
const {ccclass, property} = cc._decorator;
@ccclass
export default class TestScript extends cc.Component
{
private x: number = 15;
private y: number = 15;
start()
{
this.function1();
}
function1()
{
const sprite = this.node.getChildByName("spriteName");
sprite.active = true;
const moveAndDisable = cc.sequence(
cc.moveTo(1, this.x, this.y),
cc.callFunc(() => this.function2()));
sprite.runAction(moveAndDisable);
}
function2()
{
this.node.getChildByName("spriteName").active = false;
}
}
如果您希望以不同的持续时间同时移动多个对象,但希望在所有对象都完成移动后运行一个方法,您可以将 cc.tween
与 Promise
类结合使用。
const {ccclass, property} = cc._decorator;
@ccclass
export default class TestScript extends cc.Component
{
@property(cc.Sprite)
private sprite1: cc.Sprite = null;
@property(cc.Sprite)
private sprite2: cc.Sprite = null;
@property(cc.Sprite)
private sprite3: cc.Sprite = null;
private x: number = 15;
private y: number = 15;
start()
{
this.function1();
}
function1()
{
Promise
.all([
this.moveNodeToPosition(this.sprite1.node, cc.v3(this.x, this.y, 0), 1.0),
this.moveNodeToPosition(this.sprite2.node, cc.v3(this.x, this.y, 0), 1.5),
this.moveNodeToPosition(this.sprite3.node, cc.v3(this.x, this.y, 0), 2.0),
])
.then(this.function2);
}
function2()
{
cc.log("done");
}
moveNodeToPosition(
target: cc.Node,
position: cc.Vec3,
duration: number) : Promise<unknown>
{
return new Promise(resolve =>
{
cc.tween(target)
.to(duration, { position: position })
.call(() => resolve(null))
.start();
});
}
}