我试图使用CCSequence和CCRepeatForever在屏幕上上下移动CCSprite,但我一直收到错误。我的方法的代码如下所示,抛出异常的代码行标有注释。
-(void) beginMovingAtSpeed: (float) speed
{
CGSize viewSize = [[CCDirector sharedDirector] viewSize];
float yMin = viewSize.height * .14f;
float yMax = viewSize.height * .86f;
CGPoint start = self.position; // here you will get the current position of your sprite.
CGPoint end = ccp(self.position.x,yMax);
float distance = ccpDistance(start, end); // now you have the distance
float duration = distance/speed; // here you find the duration required to cover the distance at constant speed
CCActionMoveTo* firstMove = [CCActionMoveTo actionWithDuration:duration position:CGPointMake(self.position.x, yMin)];
CCActionMoveTo* secondMove = [CCActionMoveTo actionWithDuration:speed position:CGPointMake(self.position.x, yMax)];
CCActionMoveTo* thirdMove = [CCActionMoveTo actionWithDuration:speed position:CGPointMake(self.position.x, yMin)];
id repeatSequence = [CCActionRepeatForever actionWithAction:[CCActionSequence actionOne:secondMove two:thirdMove]];
// THIS IS THE OFFENDING LINE
CCActionSequence* finalSequence = [CCActionSequence actionOne:firstMove two:repeatSequence];
[self runAction: finalSequence];
}
以防其他人遇到此问题,CCActionCallBlock是我的解决方案,以下代码是我的解决方法:
{
CGSize viewSize;
float yMin;
float yMax;
}
-(void) beginMovingAtSpeed: (float) speed
{
viewSize = [[CCDirector sharedDirector] viewSize];
yMin = viewSize.height * .14f;
yMax = viewSize.height * .86f;
CGPoint start = self.position; // here you will get the current position of your sprite.
CGPoint end = ccp(self.position.x,yMax);
float distance = ccpDistance(start, end); // now you have the distance
float duration = distance/speed; // here you find the duration required to cover the distance at constant speed
CCActionMoveTo* firstMove = [CCActionMoveTo actionWithDuration:duration position:CGPointMake(self.position.x, yMin)];
CCActionSequence* sequence = [CCActionSequence actionOne:firstMove two:
[CCActionCallBlock actionWithBlock:^
{
[self performSelector:@selector(startAutomaticBarMovement:) withObject:[NSNumber numberWithFloat:speed]];
}]];
[self runAction: sequence];
}
-(void) startAutomaticBarMovement: (NSNumber*) duration
{
CCActionMoveTo* secondMove = [CCActionMoveTo actionWithDuration:[duration floatValue] position:CGPointMake(self.position.x, yMax)];
CCActionMoveTo* thirdMove = [CCActionMoveTo actionWithDuration:[duration floatValue] position:CGPointMake(self.position.x, yMin)];
[self runAction: [CCActionRepeatForever actionWithAction:
[CCActionSequence actionOne:secondMove two:thirdMove]]];
}