嗨,我正在用 cocos2d 制作游戏。我想用NSTimer
. 对象存储在一个NSArray
。我使用以下方式,但每次计时器初始化时都会发生同样的事情。就像随机不起作用一样。我感觉不妥。如果你能告诉我哪里出了问题,我会很高兴。或者简单地告诉我如何访问数组的随机对象。
-(id)init{
if (self = [super init]) {
....
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(randomObjects) userInfo:nil repeats:NO];
....
}
return self;
}
-(void)randomObjects{
if (!isPaused) {
srand(time(NULL));
int randomObjectIndex = rand()%self.ObjectCount_forThisLevel;
NSLog(@"randomObjectIndex = %d",randomObjectIndex);
int randomObjectID = [[self.arrayForObjects objectAtIndex:randomObjectIndex] intValue];
NSLog(@"randomObjectID = %d",randomObjectID);
switch (randomObjectID) {
case kBoxObject:{
srand(time(NULL));
int x1 = rand()%200+100;
[self createBoxAtLocation:CGPointMake(x1, 500)];
break;
}
case kBrickObject:{
srand(time(NULL));
int x2 = rand()%200+100;
[self createBrickAtLocation:CGPointMake(x2, 500)];
break;
}
case kOrangeObject:{
srand(time(NULL));
int x3 = rand()%200+100;
[self createOrangeAtLocation:CGPointMake(x3, 500)];
break;
}
case kBoardObject:{
srand(time(NULL));
int x4 = rand()%200+100;
[self createBoardAtLocation:CGPointMake(x4, 500)];
break;
}
default:
break;
}
}
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(randomObjects) userInfo:nil repeats:NO];
}