Game Development Reference
In-Depth Information
float radius = arc4random()%8+8;
float x = radius + arc4random()%(int)(gameAreaSize.width+radius*2);
CGPoint center = CGPointMake(x, -radius);
NSString* imageName = [[Asteroid02 imageNameVariations] objectAtIndex:arc4random()%3];
Asteroid02* asteroid = [[Asteroid02 alloc] initAt:center WithRadius:radius AndImage: imageName];
float speed = (arc4random()%10)/10.0 + .1;
[asteroid setSpeed: speed];
return asteroid;
}
+(NSMutableArray*)imageNameVariations{
if (imageNameVariations == nil){
imageNameVariations = [NSMutableArray new];
[imageNameVariations addObject:@"AsteroidA"];
[imageNameVariations addObject:@"AsteroidB"];
[imageNameVariations addObject:@"AsteroidC"];
}
return imageNameVariations;
}
-(void)step:(Example02Controller*)controller{
CGPoint newCenter = self.center;
newCenter.y += self.speed;
self.center = newCenter;
if (newCenter.y - self.radius > controller.gameAreaSize.height){
[controller removeActor: self];
}
}
@end
In Listing 5-12, the constructor task asteroid: creates a new Asteroid02 object and sets up its
starting state. For variety, each asteroid is assigned a random radius and a random X location. The
starting Y location is set to negative radius , so the asteroid starts just off the top of the game area.
Each Asteroid02 is also assigned a random speed .
The task step: implements the motion of the Asteroid02 —it simply increases the Y value of the
property center by speed until it reaches the bottom of the game area, where it removes itself from
the game.
As mentioned, we want the graphic used to represent the Asteroid02 to have some variety as
well. To implement this, we have the task imageNameVariations that lazily populates the global
NSMutableArray imageNameVariations . In the task asteroid: , a random string is pulled from this
array and set as the Asteroids. Figure 5-8 shows the image files used in this example.
Search WWH ::




Custom Search