本文共 2335 字,大约阅读时间需要 7 分钟。
本章我们将以一个垂直射击游戏为题材,带领大家动手制作一个简单的游戏,主要目的是让大家对Cocos2D开发游戏有一个感性的认识,同时体验Cocos2D的强大以及易用性。之后的章节将引入更多的游戏元素,逐步完善此游戏。
作为开发者,首先需要有一台iOS设备,iPhone、iPod Touch或者iPad都可以;其次要拥有开发者账号,按照第1章介绍的方法下载并安装开发者证书,这样才可以把游戏编译运行到真机上。
为什么非要真机呢?接下来向大家展示的游戏必须有真机才能测试,游戏将使用加速计控制飞机的飞行,而在模拟器里是无法处理加速计事件的。打开Xcode,使用Cocos2D iOS模板新建一个项目,将其命名为VerticalShootingGame,单击“Next”;选择一个目录单击“Create”。编译运行将看到经典的Hello World画面。本节我们将构建一个垂直射击游戏。模拟器的默认方向是横向(Landscape),因此需要把设备方向发成垂直方向的,同时清除模板内容,为后面的工作做准备。步骤1 打开AppDelegate.m,找到如代码清单2-1所示的代码。代码清单2-1 打开AppDelegate.m的代码// Supported orientations: Landscape. Customize it for your own needs- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{ returnUIInterfaceOrientationIsLandscape(interfaceOrientation);}
找到以下语句:
returnUIInterfaceOrientationIsLandscape(interfaceOrientation)
改成以下语句即可:
returnUIInterfaceOrientationIsPortrait(interfaceOrientation)
这时编译运行结果如图2-1所示。
步骤2 清除这个Hello World场景,同时去掉GameCenter的Achievement和Leaderboard。1)打开HelloWorldLayer.h,使用代码清单2-2所示代码替换。
代码清单2-2 替换HelloWorldLayer.h代码// When you import this file, you import all the Cocos2D classes#import "Cocos2D.h"// HelloWorldLayer@interface HelloWorldLayer : CCLayer {}// returns a CCScene that contains the HelloWorldLayer as the only child+(CCScene *) scene;@end
以上操作主要是删除对GameKit头文件的引用,同时移除GKAchievementViewControllerDelegate和GKLeaderboardViewControllerDelegate两个代理协议,因为在本章内容中暂时不会涉及Game Gener。
2)打开HelloWorldLayer.m,把init方法用代码清单2-3所示代码替换掉。代码清单2-3 替换init方法代码// on "init" you need to initialize your instance-(id) init{ // always call "super" init // Apple recommends to re-assign "self" with the "super's" return value if( (self=[super init]) ) { } return self;}
3)把GameKit相关的代理方法删除,找到代码清单2-4所示代码直接删除。
代码清单2-4 GameKit相关代理方法的待删除代码#pragma mark GameKit delegate-(void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController{ AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; [[appnavController] dismissModalViewControllerAnimated:YES];} -(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController{ AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; [[appnavController] dismissModalViewControllerAnimated:YES];}
编译运行得到如图2-2所示结果。
好,空空如也,没关系,这正是下一个游戏的伟大起点。
转载地址:http://vjeal.baihongyu.com/