這三年多的時間,我從一個不知道hello_world是什么的小毛小子,到現在開始一點點的進階,感觸頗多.不過幸運的是,我沒有把自己的人生旅途交給老天,我更多的交給了我自己.我無時無刻的對自己說 ,加油~ 也是對看這篇博文的你,加油.因為你已經度過了 ?c->oc->ios的過渡.相信吧,功夫不負有心人.
~來,搞起來,我那和我親密無間的 helloWorld!


1.代理文件的解讀
1).h文件代碼如下
~~~
//
// AppDelegate.h
// HelloWorld2D
//
// Created by lichan on 13-12-7.
// Copyright com.lichan 2013年. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "cocos2d.h"
// Added only for iOS 6 support
@interface MyNavigationController : UINavigationController <CCDirectorDelegate>
@end
@interface AppController : NSObject <UIApplicationDelegate>
{
UIWindow *window_;
MyNavigationController *navController_;
CCDirectorIOS *director_; // weak ref
}
@property (nonatomic, retain) UIWindow *window;
@property (readonly) MyNavigationController *navController;
@property (readonly) CCDirectorIOS *director;
@end
~~~
和IOS最大的區別在于 協議的不同和 屬性的增加.
UINavigationController <CCDirectorDelegate> ?繼承與導航控制器,并遵守 導演代理.
導航控制器我就不多說了,導演代理是什么呢?相比較而言,就相當于 我們的NSOBject類.導演代理講會安排我們里面的所有圖層,動作等.
CCDirectorIOS*director_;我們定義了一個導演的實體對象,便于調用.
2).m文件有何不一樣?
~~~
//
// AppDelegate.m
// HelloWorld2D
//
// Created by lichan on 13-12-7.
// Copyright com.lichan 2013年. All rights reserved.
//
#import "cocos2d.h"
#import "AppDelegate.h"
#import "IntroLayer.h"
@implementation MyNavigationController
// The available orientations should be defined in the Info.plist file.
// And in iOS 6+ only, you can override it in the Root View controller in the "supportedInterfaceOrientations" method.
// Only valid for iOS 6+. NOT VALID for iOS 4 / 5.
-(NSUInteger)supportedInterfaceOrientations { //關于機器類型的選擇.
// iPhone only
if( [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone )
return UIInterfaceOrientationMaskLandscape;
// iPad only
return UIInterfaceOrientationMaskLandscape;
}
// Supported orientations. Customize it for your own needs
// Only valid on iOS 4 / 5. NOT VALID for iOS 6.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// iPhone only //是否設置旋轉
if( [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone )
return UIInterfaceOrientationIsLandscape(interfaceOrientation);
// iPad only
// iPhone only
return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
// This is needed for iOS4 and iOS5 in order to ensure
// that the 1st scene has the correct dimensions
// This is not needed on iOS6 and could be added to the application:didFinish...
-(void) directorDidReshapeProjection:(CCDirector*)director //關于 導演類的加載
{
if(director.runningScene == nil) {
// Add the first scene to the stack. The director will draw it immediately into the framebuffer. (Animation is started automatically when the view is displayed.)
// and add the scene to the stack. The director will run it when it automatically when the view is displayed.
[director runWithScene: [IntroLayer scene]];
}
}
@end
@implementation AppController
@synthesize window=window_, navController=navController_, director=director_;//get方法的別名
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Create the main window//老規矩! 這都是啟動加載的東西
window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// CCGLView creation
// viewWithFrame: size of the OpenGL view. For full screen use [_window bounds]
// - Possible values: any CGRect
// pixelFormat: Format of the render buffer. Use RGBA8 for better color precision (eg: gradients). But it takes more memory and it is slower
// - Possible values: kEAGLColorFormatRGBA8, kEAGLColorFormatRGB565
// depthFormat: Use stencil if you plan to use CCClippingNode. Use Depth if you plan to use 3D effects, like CCCamera or CCNode#vertexZ
// - Possible values: 0, GL_DEPTH_COMPONENT24_OES, GL_DEPTH24_STENCIL8_OES
// sharegroup: OpenGL sharegroup. Useful if you want to share the same OpenGL context between different threads
// - Possible values: nil, or any valid EAGLSharegroup group
// multiSampling: Whether or not to enable multisampling
// - Possible values: YES, NO
// numberOfSamples: Only valid if multisampling is enabled
// - Possible values: 0 to glGetIntegerv(GL_MAX_SAMPLES_APPLE)
CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds]
pixelFormat:kEAGLColorFormatRGB565
depthFormat:0
preserveBackbuffer:NO
sharegroup:nil
multiSampling:NO
numberOfSamples:0];
//建立一個視圖,可以認為是根視圖,最后加載到 window 的視圖上面
director_ = (CCDirectorIOS*) [CCDirector sharedDirector]; //得到導演類的實體
director_.wantsFullScreenLayout = YES; 是否設置全屏
// Display FSP and SPF
[director_ setDisplayStats:YES]; // //是否顯示 tsp /spf
// set FPS at 60
[director_ setAnimationInterval:1.0/60]; //游戲的刷新頻率
// attach the openglView to the director
[director_ setView:glView]; //把根視圖給 導演實體,讓他來處理
// 2D projection
[director_ setProjection:kCCDirectorProjection2D]; //設置為2d映像
// [director setProjection:kCCDirectorProjection3D];
// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
if( ! [director_ enableRetinaDisplay:YES] )
CCLOG(@"Retina Display Not supported");//看看我們的機器是否支持最新的 Retina 分辨率
// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
// You can change this setting at any time.
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];//支持的texture類型,加載圖片用的
// If the 1st suffix is not found and if fallback is enabled then fallback suffixes are going to searched. If none is found, it will try with the name without suffix.
// On iPad HD : "-ipadhd", "-ipad", "-hd"
// On iPad : "-ipad", "-hd"
// On iPhone HD: "-hd"
CCFileUtils *sharedFileUtils = [CCFileUtils sharedFileUtils];
[sharedFileUtils setEnableFallbackSuffixes:NO]; // Default: NO. No fallback suffixes are going to be used
[sharedFileUtils setiPhoneRetinaDisplaySuffix:@"-hd"]; // Default on iPhone RetinaDisplay is "-hd"
[sharedFileUtils setiPadSuffix:@"-ipad"]; // Default on iPad is "ipad"
[sharedFileUtils setiPadRetinaDisplaySuffix:@"-ipadhd"]; // Default on iPad RetinaDisplay is "-ipadhd"
// Assume that PVR images have premultiplied alpha
[CCTexture2D PVRImagesHavePremultipliedAlpha:YES];
// Create a Navigation Controller with the Director
navController_ = [[MyNavigationController alloc] initWithRootViewController:director_];把導演實體作為到航視圖的跟控制類
navController_.navigationBarHidden = YES;
// for rotation and other messages
[director_ setDelegate:navController_];
// set the Navigation Controller as the root view controller
[window_ setRootViewController:navController_];
// make main window visible
[window_ makeKeyAndVisible];
return YES;
}
// getting a call, pause the game
-(void) applicationWillResignActive:(UIApplication *)application//這四個就是代理的四種方法,出現,消失,進后臺,出后臺,中斷
{
if( [navController_ visibleViewController] == director_ )
[director_ pause];
}
// call got rejected
-(void) applicationDidBecomeActive:(UIApplication *)application
{
[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
if( [navController_ visibleViewController] == director_ )
[director_ resume];
}
-(void) applicationDidEnterBackground:(UIApplication*)application
{
if( [navController_ visibleViewController] == director_ )
[director_ stopAnimation];
}
-(void) applicationWillEnterForeground:(UIApplication*)application
{
if( [navController_ visibleViewController] == director_ )
[director_ startAnimation];
}
// application will be killed
- (void)applicationWillTerminate:(UIApplication *)application
{
CC_DIRECTOR_END();
}
// purge memory
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
[[CCDirector sharedDirector] purgeCachedData];
}
// next delta time will be zero
-(void) applicationSignificantTimeChange:(UIApplication *)application
{
[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}
- (void) dealloc
{
[window_ release];
[navController_ release];
[super dealloc];
}
@end
~~~
2.HelloWorldlayer文件的解讀
1).h文件
~~~
//
// HelloWorldLayer.h
// HelloWorld2D
//
// Created by lichan on 13-12-7.
// Copyright com.lichan 2013年. All rights reserved.
//
#import <GameKit/GameKit.h>
// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"
// HelloWorldLayer
@interface HelloWorldLayer : CCLayer <GKAchievementViewControllerDelegate, GKLeaderboardViewControllerDelegate>
{
}
// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene; //這個類方法是干什么的呢?因為導演類只可以加載CCScene對象,而IntroLayer 繼承與Layer,這里是轉化為導演可以接受的對象.
@end
~~~
2)我們再去看看.m文件吧
~~~
//
// HelloWorldLayer.m
// HelloWorld2D
//
// Created by lichan on 13-12-7.
// Copyright com.lichan 2013年. All rights reserved.
//
// Import the interfaces
#import "HelloWorldLayer.h"
// Needed to obtain the Navigation Controller
#import "AppDelegate.h"
#pragma mark - HelloWorldLayer
// HelloWorldLayer implementation
@implementation HelloWorldLayer
// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
// 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]) ) {
// create and initialize a Label
CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello World" fontName:@"Marker Felt" fontSize:64];
// ask director for the window size
CGSize size = [[CCDirector sharedDirector] winSize];
//得到我們的導演類的尺寸.
// position the label on the center of the screen
label.position = ccp( size.width /2 , size.height/2 );
//設置helloWorld 在view中的位置.ccp 一個新的方法哦
// add the label as a child to this Layer
[self addChild: label]; //增加到視圖中去
//上述代碼無非就是增加一個 HelloWorld的 label.但是這個字體可是 @"Marker Felt".字體大小64的.
?
~~~
~~~
~~~
~~~
//其實下面的代碼 是 設置 一個飛機小精靈.然后設置位置 并設置他飛行的路徑.(到某個位置.)
CCSprite *plane = [CCSprite spriteWithFile:@"plane.png"];
plane.position = ccp(size.width/2, size.height*0.7);
[self addChild:plane];
id flyAction = [CCMoveTo actionWithDuration:4 position:ccp(size.width+200, size.height)];//設置的動作的方法. 其中還有CCMoveBy ,這兩種action都是非常常見的
[plane runAction:flyAction];//讓飛機飛起來
//
// Leaderboards and Achievements
//
// Default font size will be 28 points.
[CCMenuItemFont setFontSize:28];
// to avoid a retain-cycle with the menuitem and blocks
__block id copy_self = self;
// Achievement Menu Item using blocks
CCMenuItem *itemAchievement = [CCMenuItemFont itemWithString:@"Achievements" block:^(id sender) {
GKAchievementViewController *achivementViewController = [[GKAchievementViewController alloc] init];
achivementViewController.achievementDelegate = copy_self;
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] presentModalViewController:achivementViewController animated:YES];
[achivementViewController release];
}];
// Leaderboard Menu Item using blocks
CCMenuItem *itemLeaderboard = [CCMenuItemFont itemWithString:@"Leaderboard" block:^(id sender) {
GKLeaderboardViewController *leaderboardViewController = [[GKLeaderboardViewController alloc] init];
leaderboardViewController.leaderboardDelegate = copy_self;
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] presentModalViewController:leaderboardViewController animated:YES];
[leaderboardViewController release];
}];
CCMenu *menu = [CCMenu menuWithItems:itemAchievement, itemLeaderboard, nil];
[menu alignItemsHorizontallyWithPadding:20];
[menu setPosition:ccp( size.width/2, size.height/2 - 50)];
// Add the menu to the layer
[self addChild:menu];
}
return self;
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
// in case you have something to dealloc, do it in this method
// in this particular example nothing needs to be released.
// cocos2d will automatically release all the children (Label)
// don't forget to call "super dealloc"
[super dealloc];
}
#pragma mark GameKit delegate
-(void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] dismissModalViewControllerAnimated:YES];
}
-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] dismissModalViewControllerAnimated:YES];
}
@end
~~~