我如何创建一个循环的函数,并改变精灵的位置?

时间:2011-06-17 20:03:33

标签: function loops cocos2d-iphone position ccsprite

所以我需要一个功能或能让我的2个精灵一直上下移动的东西!从应用程序开始,屏幕上已触摸任何内容..

继承人我试图做的事情,但因为它在我的init中,它只运行一次.. 我怎样才能使这个循环成为自我,所以它看起来很动态?

if (bgSkyer == false) {
            [bg3 runAction:[CCMoveTo actionWithDuration:0.5 position:ccp(240,100)]];
            [bg2 runAction:[CCMoveTo actionWithDuration:1.5 position:ccp(240,95)]];
            bgSkyer = true;
        }else {
            [bg3 runAction:[CCMoveTo actionWithDuration:0.5 position:ccp(240,112)]];
            [bg2 runAction:[CCMoveTo actionWithDuration:1.5 position:ccp(240,80)]];
            bgSkyer = false;
        }

2 个答案:

答案 0 :(得分:1)

如Jebego的回答所示,您需要使用CCRepeatForever。但是,假设您使用bgSkyer作为标记在两个位置之间切换,如果您将CCRepeatForeverCCSequence一起使用,我们可以使用跳过该标记,如下所示(显式)变量用于清晰,但如果你愿意,你总是可以将它们合并成一行:

CCMoveTo *moveTo_240_95 = [CCMoveTo actionWithDuration:1.5 position:ccp(240,95)];
CCMoveTo *moveTo_240_80 = [CCMoveTo actionWithDuration:1.5 position:ccp(240,80)];
CCSequence *actionsForBg2 = [CCSequence actions:moveTo_240_95, moveTo_240_80, nil];
CCAction *repeatForBg2 = [CCRepeatForever actionWithAction:actionsForBg2];
[bg2 runAction:repeatForBg2]

CCMoveTo *moveTo_240_100 = [CCMoveTo actionWithDuration:0.5 position:ccp(240,100)];
CCMoveTo *moveTo_240_112 = [CCMoveTo actionWithDuration:0.5 position:ccp(240,112)];
CCSequence *actionsForBg3 = [CCSequence actions:moveTo_240_100, moveTo_240_112, nil];
CCAction *repeatForBg3 = [CCRepeatForever actionWithAction:actionsForBg3];
[bg3 runAction:repeatForBg3]

CCSequence执行您在序列中一个接一个地传递给它的操作,CCRepeatForever将永远重复该序列,直到您在节点上调用[node stopAllActions]或直到该节点为dealloc “编

答案 1 :(得分:0)

我认为这样的事情可能就是你要找的东西:

if (bgSkyer == false) {
    CCMoveTo *moveOne = [CCMoveTo actionWithDuration:0.5 position:ccp(240,100)];
    CCRepeatForever *repeatOne = [CCRepeatForever actionWithAction:moveOne];
    [bg3 runAction:repeatOne];

    CCMoveTo *moveTwo = [CCMoveTo actionWithDuration:1.5 position:ccp(240,95)];
    CCRepeatForever *repeatTwo = [CCRepeatForever actionWithAction:moveTwo];
    [bg3 runAction:repeatTwo];
}else{
    //just repeat code, etc...
}

希望它有效!