我有3个不同的精灵。我想连续动画从屏幕底部进入的这三个不同的精灵,随着进入的物体数量的增加而增加速度。此外,这三个应该是随机顺序。
所以,我尝试使用以下代码来获取任何随机顺序的三个sprite中的任何一个,但它没有按预期工作:
int randomNumber;
for (int i = 1; i<500; i++) {
randomNumber = arc4random_uniform(3);
NSLog(@"Value of random Number %d" ,randomNumber);
if (randomNumber == 0) {
[self addRedBall];
SKAction *moveBall = [SKAction moveToY:CGRectGetMaxY(self.frame) duration:5];
dispatch_queue_t actionDispatchRed;
actionDispatchRed = dispatch_queue_create("com.redball.dispatch", NULL);
dispatch_async(actionDispatchRed, ^ { [redBall runAction:moveBall]; });
[NSThread sleepForTimeInterval:2]; //Time interval to wait before the next ball comes in.
}
else if (randomNumber == 1) {
[self addBlueBall];
dispatch_queue_t actionDispatchBlue;
SKAction *moveBall = [SKAction moveToY:CGRectGetMaxY(self.frame) duration:5];
actionDispatchBlue = dispatch_queue_create("com.blueball.dispatch", NULL);
dispatch_async(actionDispatchBlue, ^{ [blueBall runAction:moveBall]; });
[NSThread sleepForTimeInterval:2];
}
else if (randomNumber == 2) {
[self addGreenBall];
SKAction *moveBall = [SKAction moveToY:CGRectGetMaxY(self.frame) duration:5
];
dispatch_queue_t actionDispatchGreen;
actionDispatchGreen = dispatch_queue_create("com.greenball.dispatch", NULL);
dispatch_async(actionDispatchGreen,
^ { [greenBall runAction:moveBall]; } );
[NSThread sleepForTimeInterval:2];
}
}
当我使用[NSThread sleepForTimeInterval:2]时; ,程序不会比起始屏幕更进一步。
当我尝试在没有sleepForTimeInterval的情况下运行程序时,会有大量的精灵进入并相互重叠,导致只有一个可见的精灵。
请帮忙。
答案 0 :(得分:1)
我不建议使用[NSThread sleepForTimeInterval:2];
而是尝试使用[self performSelector:@selector(addBall) withObject:nil afterDelay:2];
-(void)addBall
{
self.addedBall++;
if (self.addedBall > 500)
{
return;
}
randomNumber = arc4random_uniform(3);
if (randomNumber == 0) {
[self addRedBall];
SKAction *moveBall = [SKAction moveToY:CGRectGetMaxY(self.frame) duration:5];
dispatch_queue_t actionDispatchRed;
actionDispatchRed = dispatch_queue_create("com.redball.dispatch", NULL);
dispatch_async(actionDispatchRed, ^ { [redBall runAction:moveBall]; });
[self performSelector:@selector(addBall) withObject:nil afterDelay:2];
}
//other else if stuff
}
此外,我不确定您为什么在dispatch_queue中运行SKActions,可能不需要。
我希望有所帮助。