extracts from 《Beginning iPhone Games Development》
iOS extracts: The Illusion of Motion
To create the illusion of motion on a screen, movies and TV use still frames presented inquick succession, one after the other, within a short lapse of time. This is the origin ofthe termframes per secondused in video performance. In games programming, thedisplay logic is ideally performed at least 30 times per second, to give the illusion ofsmoothly moving images on the screen.
On the iPhone, a class calledNSTimer, provided by Foundation framework, lets youschedule a method to be called repeatedly, several times per second. We will now writea method to modify the ball's position over time, to make it bounce around the screen,usingNSTimer.
NOTE:There is a new way to create a timer in iPhone SDK 3.1, calledCADisplayLink, whichis more appropriate for games.CADisplayLinksynchronizes with the iPhone display, which isguaranteed to refresh 60 times per second. We will continue this game example usingNSTimer,but switch the code to useCADisplayLinkat the end of the chapter.
Listing 3–9. Add the ivar ballMovement to the view controller's interface.
@interface IVBrickerViewController : UIViewController {
UILabel *scoreLabel;
int score;UIImageView *ball;CGPoint ballMovement;
}
@property (nonatomic, retain) IBOutlet UILabel *scoreLabel;@property (nonatomic, retain) IBOutlet UIImageView *ball;
- (void)initializeTimer;
- (void)animateBall:(NSTimer *)theTimer;
@end
This code adds another instance variable to the view controller, calledballMovement,which holds the number of pixels that the ball will move per frame.CGPointis a Cstructure provided by the Core Graphics framework. It has X and Y attributes, which letus specify different rates of movement vertically and horizontally. We also declare thesignature for the methods initializeTimerand animateBall:.
Next, open the fileIVBrickerViewController.m. Remove the comments around theviewDidLoadmethod, and then apply the changes shown in bold in Listing 3–10. Notethe code for the methodsinitializeTimerand animateBall:.
Listing 3–10. Here are the implementations of the viewDidLoad, initializeTimer, and animateBall: methods in theview controller.
- (void)viewDidLoad {
[super viewDidLoad];
ballMovement = CGPointMake(4,4);
[self initializeTimer];
}
- (void)initializeTimer {
float theInterval = 1.0/30.0;
[NSTimer scheduledTimerWithTimeInterval:theInterval target:self
selector:@selector(animateBall:) userInfo:nil repeats:YES];
}
- (void)animateBall:(NSTimer *)theTimer {
ball.center = CGPointMake(ball.center.x+ballMovement.x,
ball.center.y+ballMovement.y);
if(ball.center.x > 300 || ball.center.x < 20)
ballMovement.x = -ballMovement.x;
if(ball.center.y > 440 || ball.center.y < 40)
ballMovement.y = -ballMovement.y;
}
This implements theviewDidLoad,initializeTimer, andanimateBall:methods in theview controller.viewDidLoadsets an initial value to theballMovementinstance variable,of 4 pixels vertically by 4 pixels horizontally. Next, it calls theinitializeTimermethod.TheinitializeTimermethod creates anNSTimerinstance, initializing it to call theanimateBall:method 30 times per second.
The animateBall:method begins by taking the ball center coordinates and adjusting itby the values of the correspondingballMovementcoordinates. This effectively moves theball by 4 pixels vertically and horizontally every frame. The remaining lines of code inanimateBall:check whether the ball has reached any of the four edges of the screen. Ifit has, the code reverses the direction of ball movement by changing the value of thecoordinate from 4 to -4 and vice versa. For example, if the ball is moving left to right andit reaches the right edge, the ball “bounces” off the edge and starts moving to the left.
You may notice the current code withinanimateBall:does not make use of theNSTimerobject that is passed in as a parameter. This object will come in handy later on in thechapter. For example, we will add code to stop the timer when the player loses a life andwhen the game is over.
Save your work. Now build and run the project, and behold the greatness of iPhoneanimated 2D graphics on the simulator.
Now that we have some motion going on, let's add some user interaction.
NOTE:In this simple example, I am putting game state and game logic code in the viewcontroller. When designing large games with a lot of enemies, obstacles, and many other gameelements to keep track of, it is more organized to create several classes to contain a model ofwhat is happening on the screen and to separate the game logic code from game model code.The view controller's job then becomes simpler, as it just needs to send input events to the gamelogic and update the view according to the game model. Separating model code, view code, andcontroller code is called the Model-View-Controller design pattern.