精灵位置变化之间的延迟

时间:2012-09-30 14:00:24

标签: objective-c for-loop cocos2d-iphone sprite

现在我的NSArray里面有x个坐标;我有一个精灵,需要去每个点沿着选定的路径前进。我尝试使用for循环,但这样做很快,它似乎只是传送到最终目的地。我已经尝试了选择器,但我也无法让它们工作。有谁知道怎么做?

2 个答案:

答案 0 :(得分:0)

你必须使用NSTimer

@implementation whatever
{
int count;
NSTimer *myTimer;
CCSprite *mySprite;
NSArray *locationArray;
}

然后从某个地方启动计时器......

 count=0
 //1.0 is one second, so change it to however long you want to wait between position changes
 myTimer =   [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(movealong) userInfo:nil repeats:YES];

然后它调用它直到它遍历所有对象

-(void)movealong{

//assuming array is full of CGPoints...
//mySprite.position = [locationArray objectAtIndex:count];
//try this then
CGPoint newPoint = [locationArray objectAtIndex:count];
mySprite.position = ccp(newPoint.x,newPoint.y);
//I think maybe THIS is what you need to do to make it work... 
//if you want it to not jump directly there
//you can also use CCMoveTo 
/*//  under actionWithDuration: put the same amount of time or less of what you had
  //  under scheduledTimerWithTimeInterval in your NSTimer
    CCFiniteTimeAction *newPos = [CCMoveTo actionWithDuration:1.0 position:[locationArray objectAtIndex:count]];
    [mySprite runAction:newPos];
*/
count++;
if(count >= locationArray.count){
    [myTimer invalidate];
    myTimer = nil;
}
}

答案 1 :(得分:0)

创建一个方法,将精灵放置在位置数组中某个索引处(例如_i)的位置。并且在此方法结束时再次使用延迟,依次使用CCDelayTime和CCCallFunc操作来调用它。并且不要忘记增加索引。像Smth一样

// somewhere in code to start move
_i = 0;
[self setNewPosition];

// method that will set the next position
- (void) setNewPosition
{
    sprite.position = // get position at index _i from your array here
    _i++;

    BOOL needSetNextPosition = // check if _i is inside bounds of your positions array
    if( needSetNextPosition )
    {
        id delay = [CCDelayTime actionWithDuration: delayBetweenUpdate];
        id callback = [CCCallFunc actionWithTarget: self selector: @selector(setNewPosition)];
        id sequence = [CCSequence actionOne: delay two: callback];
        [self runAction = sequence];
    }

}

这只是一个例子,但我希望,您可以根据自己的需要进行调整。