1:我的Cocoa-2d之HelloWorld
最后更新于:2022-04-01 20:14:54
这三年多的时间,我从一个不知道hello_world是什么的小毛小子,到现在开始一点点的进阶,感触颇多.不过幸运的是,我没有把自己的人生旅途交给老天,我更多的交给了我自己.我无时无刻的对自己说 ,加油~ 也是对看这篇博文的你,加油.因为你已经度过了 c->oc->ios的过渡.相信吧,功夫不负有心人.
~来,搞起来,我那和我亲密无间的 helloWorld!
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-22_57bab557821d8.jpg)
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-22_57bab557a6dab.jpg)
1.代理文件的解读
1).h文件代码如下
~~~
//
// AppDelegate.h
// HelloWorld2D
//
// Created by lichan on 13-12-7.
// Copyright com.lichan 2013年. All rights reserved.
//
#import
#import "cocos2d.h"
// Added only for iOS 6 support
@interface MyNavigationController : UINavigationController
@end
@interface AppController : NSObject
{
UIWindow *window_;
MyNavigationController *navController_;
CCDirectorIOS *director_; // weak ref
}
@property (nonatomic, retain) UIWindow *window;
@property (readonly) MyNavigationController *navController;
@property (readonly) CCDirectorIOS *director;
@end
~~~
和IOS最大的区别在于 协议的不同和 属性的增加.
UINavigationController 继承与导航控制器,并遵守 导演代理.
导航控制器我就不多说了,导演代理是什么呢?相比较而言,就相当于 我们的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
// 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; //这个类方法是干什么的呢?因为导演类只可以加载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
~~~
';