IOS_Cocos2D_结点_精灵_消息调试(定时器)

H:/0925/01-cocos2d入门_0WorldLayer.h
//
//  HelloWorldLayer.h
//  01-第一个cocos2d程序
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
//


#import <GameKit/GameKit.h>


#import "cocos2d.h"


@interface HelloWorldLayer : CCLayer <GKAchievementViewControllerDelegate, GKLeaderboardViewControllerDelegate>
{
}

// 返回一个已经绑定了本图层的场景
+(CCScene *) scene;

@end

H:/0925/01-cocos2d入门_0WorldLayer.m
//
//  HelloWorldLayer.m
//  01-第一个cocos2d程序
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
#import "HelloWorldLayer.h"

// Needed to obtain the Navigation Controller
#import "AppDelegate.h"

#pragma mark - HelloWorldLayer
@implementation HelloWorldLayer

// 类方法的实现,创建一个已经绑定了本图层的场景
+(CCScene *) scene
{
	CCScene *scene = [CCScene node];
	HelloWorldLayer *layer = [HelloWorldLayer node];
	
	// 将本图层添加到场景,并返回场景
	[scene addChild: layer];
	return scene;
}

// 实例化图层对象
-(id) init
{	
	if( (self=[super init]) ) {
		// 创建一个指定内容和字体的标签
		CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello 5435435World"
							fontName:@"Marker Felt" fontSize:64];
		// 向导演索要窗口尺寸
		CGSize size = [[CCDirector sharedDirector] winSize];
		// 字符串位于屏幕中央
		label.position =  ccp( size.width /2 , size.height/2 );		
		// 标签的锚点默认是0.5 0.5
		label1.anchorPoint = CGPointMake(0, 0);
		// 将hello world标签添加到图层
		[self addChild: label];
        CCLOG(@"%@", NSStringFromCGPoint(label2.position));
		
		// CCMenuItemFont类方法,设置字体大小
		[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];
		}];

		// 将2个menuItem添加到menu
		CCMenu *menu = [CCMenu menuWithItems:itemAchievement, itemLeaderboard, nil];
		// 设置,menu里面的菜单项,内间距为20
		[menu alignItemsHorizontallyWithPadding:20];
		[menu setPosition:ccp( size.width/2, size.height/2 - 50)];
		
		// 将按钮添加到图层
		[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

H:/0925/01-cocos2d入门_AppDelegate.h
//
//  AppDelegate.h
//  01-第一个cocos2d程序
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "cocos2d.h"

// Added only for iOS 6 support
@interface MyNavigationController : UINavigationController <CCDirectorDelegate>
@end
// AppController就是主函数中,第4个参数,应用程序的代理
@interface AppController : NSObject <UIApplicationDelegate>
{
	// 成员1,window
	UIWindow *window_;
	// 成员2,导航控制器
	MyNavigationController *navController_;
	// 成员3,导演
	CCDirectorIOS	*director_;							// weak ref
}

@property (nonatomic, retain) UIWindow *window;
@property (readonly) MyNavigationController *navController;
@property (readonly) CCDirectorIOS *director;

@end

H:/0925/01-cocos2d入门_AppDelegate.m
//  AppDelegate.m
//  01-第一个cocos2d程序
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
#import "cocos2d.h"
#import "HelloWorldLayer.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_;
- (BOOL)application:(UIApplication *)application 
			didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
	// 通过主屏幕的尺寸创建窗口
	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). 但它更慢更耗内存
	//	- 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];
	// 取得导演单例
	director_ = (CCDirectorIOS*) [CCDirector sharedDirector];
	// 设置全屏布局
	director_.wantsFullScreenLayout = YES;
	
	// Display FPS and SPF
    // Frame Per Second  每秒显示多少帧,帧率,最高是60
	[director_ setDisplayStats:YES];
	
	// set FPS at 60
	[director_ setAnimationInterval:1.0/60];
	
	// attach the openglView to the director
	[director_ setView:glView];
	
	// 2D projection,只能选择2D的,3D会出现意外
	[director_ setProjection:kCCDirectorProjection2D];
	// [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");
	
	// 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];	
//    iPhone(非视网膜) -  abc.png
//    iPhone(视网膜) - abc-hd.png
//    iPad(非视网膜) - abc-ipad.png
//    iPad(视网膜) - abc-ipadhd.png
	// 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
	// 导航控制器的根控制器是导演(即UIViewController)
	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_];
	
	// 让窗口显示
	[window_ makeKeyAndVisible];
    // 导演    运行游戏的第一个场景
    [director_ runWithScene:[IntroLayer scene]];
	return YES;
}






// next delta time will be zero
-(void) applicationSignificantTimeChange:(UIApplication *)application
{	
	// setNextDeltaTimeZero什么意思?
	[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}
// call got rejected
// 代理方法,当应用获得焦点的时候,导演resume也重新获得焦点
-(void) applicationDidBecomeActive:(UIApplication *)application
{
	// setNextDeltaTimeZero什么意思?
	[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];	
	if( [navController_ visibleViewController] == director_ )
		[director_ resume];
}


- (void) dealloc
{
	[window_ release];
	[navController_ release];
	
	[super dealloc];
}
// purge 净化,清除 memory
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{	
	// 代理方法,当应用接收到内存警告时,导演清除缓存数据
	[[CCDirector sharedDirector] purgeCachedData];
}
// 代理方法,当应用即将终结时调用
- (void)applicationWillTerminate:(UIApplication *)application
{
	CC_DIRECTOR_END();
}
// 代理方法,当应用即将进入前台的时候,导演开始动画
-(void) applicationWillEnterForeground:(UIApplication*)application
{
	if( [navController_ visibleViewController] == director_ )
		[director_ startAnimation];
}
// 代理方法,当应用已经退到后台的时候,导演停止动画
-(void) applicationDidEnterBackground:(UIApplication*)application
{
	if( [navController_ visibleViewController] == director_ )
		[director_ stopAnimation];
}
// getting a call, pause the game
// 代理方法,当应用即将失去焦点的时候,导演暂停,喊KA
-(void) applicationWillResignActive:(UIApplication *)application
{
	if( [navController_ visibleViewController] == director_ )
		[director_ pause];
}
@end

H:/0925/01-cocos2d入门_IntroLayer.h
//
//  IntroLayer.h
//  01-第一个cocos2d程序
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
//


// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"


@interface IntroLayer : CCLayer
{
}

// 返回一个已经绑定了本图层的场景
+(CCScene *) scene;

@end

H:/0925/01-cocos2d入门_IntroLayer.m
//
//  IntroLayer.m
//  01-第一个cocos2d程序
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
//


#import "IntroLayer.h"
// 由于需要切换到下一个绑定了图层的场景,故导入HelloWorldLayer
#import "HelloWorldLayer.h"


#pragma mark - IntroLayer

// HelloWorldLayer implementation
@implementation IntroLayer

// Helper class method that creates a Scene 
	//with the HelloWorldLayer as the only child.
// 由于场景是不可见的最纯洁的,
// 所以图层的类方法中,创建一个场景,并向场景添加本图层,返回场景
+(CCScene *) scene
{
	// 创建一个纯洁的场景
	CCScene *scene = [CCScene node];
	
	// 创建当前图层
	IntroLayer *layer = [IntroLayer node];
	
	// 将当前图层添加到场景,并返回已经绑定图层的场景
	[scene addChild: layer];	
	return scene;
}

// 
-(id) init
{
	if( (self=[super init])) {

		// 问一个导演,window size是多少
		CGSize size = [[CCDirector sharedDirector] winSize];

		CCSprite *background;
		
		if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
			// 根据图片名 创建精灵
			background = [CCSprite spriteWithFile:@"Default.png"];
			background.rotation = 90;
		} else {
			// 如果是平板,用横屏的图片
			background = [CCSprite spriteWithFile:@"Default-Landscape~ipad.png"];
		}
		// 设置精灵的位置
		background.position = ccp(size.width/2, size.height/2);

		// 将精灵添加到图层
		[self addChild: background];
	}
	
	return self;
}

-(void) onEnter
{
	[super onEnter];
	// 导演切换场景为 图层为HelloWorldLayer的场景
	[[CCDirector sharedDirector] replaceScene:[CCTransitionRotoZoom
			transitionWithDuration:1.0 scene:[HelloWorldLayer scene] ]];
}
@end

H:/0925/01-cocos2d入门_main.m
//
//  main.m
//  01-第一个cocos2d程序
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
//

#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	// 第3个参数:nil代表默认是application
	// 第4个参数:代理的类名
    int retVal = UIApplicationMain(argc, argv, nil, @"AppController");
    [pool release];
    return retVal;
}

H:/0925/02-精灵_0WorldLayer.h
//
//  HelloWorldLayer.h
//  02-精灵
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
//


#import <GameKit/GameKit.h>

// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"


@interface HelloWorldLayer : CCLayer
// 返回一个已经包含 HelloWorld图层的场景
+(CCScene *) scene;
@end

H:/0925/02-精灵_0WorldLayer.m
//  HelloWorldLayer.m
//  02-精灵
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
#import "HelloWorldLayer.h"
// Needed to obtain the Navigation Controller
#import "AppDelegate.h"
@implementation HelloWorldLayer
// 返回了一个已经填充了图层的场景 (类方法,固定写法)
+(CCScene *) scene
{
	CCScene *scene = [CCScene node];
	HelloWorldLayer *layer = [HelloWorldLayer node];	
	[scene addChild: layer];
	return scene;
}
-(id) init
{
	if( (self=[super init]) ) {
		//调用自定义方法,向图层添加精灵
        [self addSprite3];
	}
	return self;
}
#pragma mark 添加一个精灵----1----通过纹理创建精灵
- (void)addSprite1
{
    // 1.加载纹理(只加载一次),纹理图片要小于60X60
    CCTexture2D *texture = [[CCTextureCache sharedTextureCache]
addImage:@"grossini.png"];
    // 2,向导演要屏幕尺寸
    CGSize winSize = [CCDirector sharedDirector].winSize;
    // 3.将纹理贴到精灵身上(纹理映射),通过纹理创建精灵
    CCSprite *s1 = [CCSprite spriteWithTexture:texture];
	// 4,设置下精灵的坐标
    s1.position = ccp(winSize.width * 0.5, winSize.height * 0.5);
	// 5,添加精灵到图层里
    [self addChild:s1];
}
#pragma mark 添加一个精灵----2----通过纹理创建精灵
//(指定Rect,以图片的左上角为坐标原点,截取一定区域,作为纹理)
- (void)addSprite2
{
    /*
     lufy.png  100x100  非视网膜屏幕 rect的50*50就是50*50
     lufy-hd.png 200x200 视网膜屏幕 rect的50*50却是100*100
     */
    // 1.加载纹理(只加载一次)
    CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:@"lufy.png"];
	// 2,向导演要屏幕尺寸
    CGSize winSize = [CCDirector sharedDirector].winSize;
    // 3.将纹理贴到精灵身上(纹理映射),通过纹理创建精灵,指定矩形区域
    CCSprite *s1 = [CCSprite spriteWithTexture:texture rect:CGRectMake(0, 0, 25, 25)];
    s1.position = ccp(winSize.width * 0.5, winSize.height * 0.5);
    [self addChild:s1];
}

#pragma mark 添加一个精灵----3
- (void)addSprite3
{
	// 1,向导演要屏幕尺寸
    CGSize winSize = [CCDirector sharedDirector].winSize;
	// 2,通过图片构造精灵
    CCSprite *s1 = [CCSprite spriteWithFile:@"lufy.png"];
    s1.position = ccp(winSize.width * 0.5, winSize.height * 0.5);
    [self addChild:s1];
	// opacity不透明度,晦涩难懂,0~255
    s1.opacity = 125;
    // 镜像效果 (flip 弹,翻转)
    s1.flipX = YES;
    s1.flipY = YES;
	// 着色,结构体,成员是RGB,unsigned char类型 0~255
    s1.color = ccc3(255, 0, 0);
	// 缩放
    s1.scale = 0.5;
	// 绕锚点旋转,角度值
    s1.rotation = 45;
}

@end

H:/0925/02-精灵_AppDelegate.h
//  AppDelegate.h
//  02-精灵
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
#import <UIKit/UIKit.h>
#import "cocos2d.h"
// Added only for iOS 6 support
// 导航控制器 实现了导演的代理方法
@interface MyNavigationController : UINavigationController <CCDirectorDelegate>
@end
//-------------------------------------------------------------
// AppController继承自object,遵守了UIApplicationDelegate,充当着应用程序代理的角色
/* 其成员:
		窗口,应用程序代理,都有UIWindow
		导航控制器<实现了导演的代理方法>
		导演
*/
@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

H:/0925/02-精灵_AppDelegate.m
//  AppDelegate.m
//  02-精灵
//  Created by apple on 13-9-25.
//  Copyright itcast 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_;
- (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];
	
	director_ = (CCDirectorIOS*) [CCDirector sharedDirector];
	
	director_.wantsFullScreenLayout = YES;
	
	// Display FSP and SPF
	[director_ setDisplayStats:YES];
	
	// set FPS at 60
	[director_ setAnimationInterval:1.0/60];
	
	// attach the openglView to the director
	[director_ setView:glView];
	
	// 2D projection
	[director_ setProjection:kCCDirectorProjection2D];
	//	[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");
	
	// 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];
	
	// 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

H:/0925/02-精灵_IntroLayer.h
//
//  IntroLayer.h
//  02-精灵
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
//


// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"

@interface IntroLayer : CCLayer
{
}

// returns a CCScene that contains the Intro图层 as the only child
+(CCScene *) scene;

@end

H:/0925/02-精灵_IntroLayer.m
//  IntroLayer.m
//  02-精灵
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
#import "IntroLayer.h"
// 因为导演切换场景时,要用到目标场景
#import "HelloWorldLayer.h"

#pragma mark - IntroLayer
// HelloWorldLayer implementation
@implementation IntroLayer
// 返回一个已经填充了图层的场景
+(CCScene *) scene
{
	CCScene *scene = [CCScene node];
	IntroLayer *layer = [IntroLayer node];	
	[scene addChild: layer];
	return scene;
}
// 
-(id) init
{
	if( (self=[super init])) {
		// 问导演要屏幕尺寸
		CGSize size = [[CCDirector sharedDirector] winSize];
		// 背景图片精灵
		CCSprite *background;
		
		if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
			background = [CCSprite spriteWithFile:@"Default.png"];
			background.rotation = 90;
		} else {
			background = [CCSprite spriteWithFile:@"Default-Landscape~ipad.png"];
		}
		background.position = ccp(size.width/2, size.height/2);
		[self addChild: background];
	}
	return self;
}
-(void) onEnter
{
	// 先调用父类的onEnter方法
	[super onEnter];
	// 单例导演,切换场景,with 动画
	[[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:1.0 scene:[HelloWorldLayer scene] ]];
}
@end

H:/0925/02-精灵_main.m
//
//  main.m
//  02-精灵
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
//

#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {
    
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	// 参数3:应用程序
	// 参数4:应用程序代理
    int retVal = UIApplicationMain(argc, argv, nil, @"AppController");
    [pool release];
    return retVal;
}

H:/0925/03-CCNode结点_HelloWorldLayer.h
//
//  HelloWorldLayer.h
//  03-CCNode-节点
//
//  Created by apple on 13-9-25.
//  Copyright itcast 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
+(CCScene *) scene;

@end

H:/0925/03-CCNode结点_HelloWorldLayer.m
//
//  HelloWorldLayer.m
//  03-CCNode-节点
//
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
//
#import "HelloWorldLayer.h"

// Needed to obtain the Navigation Controller
#import "AppDelegate.h"
@implementation HelloWorldLayer
+(CCScene *) scene
{	
	CCScene *scene = [CCScene node];
	HelloWorldLayer *layer = [HelloWorldLayer node];
	[scene addChild: layer];
	return scene;
}
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super's" return value
	if( (self=[super init]) ) {
        CCSprite *s = [CCSprite spriteWithFile:@"Icon.png"];
        s.anchorPoint = ccp(0, 1);
        s.position = ccp(80, 80);
        [self addChild:s z:0 tag:10];
        
        // 使得图层,能够接受触摸事件
        self.touchEnabled = YES;
	}
	return self;
}

#pragma mark 触摸结束
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CCSprite *s = (CCSprite *)[self getChildByTag:10];
    
    // 每秒钟产产闪烁两次
    CCBlink *blink = [CCBlink actionWithDuration:1 blinks:2];
    [s runAction:[CCRepeatForever actionWithAction:blink]];
    // To 目标是绝对坐标点
	//CCMoveTo *move = [CCMoveTo actionWithDuration:1 position:ccp(100, 100)];
	
	// By 参数是步长,向右,向上,顺时针为正,每次移动多少,旋转多少
    CCRotateBy *rotate = [CCRotateBy actionWithDuration:1 angle:360];
    CCMoveBy *move = [CCMoveBy actionWithDuration:1 position:ccp(100, 100)];
    CCScaleBy *scale = [CCScaleBy actionWithDuration:1 scale:0.5];
    
    CCSequence *sequence = [CCSequence actions:rotate, move, scale, nil];
    
     [s runAction:sequence];
    // CCRepeat用于包装其他的动作,指定重复次数为5次
     CCRepeat *repeat = [CCRepeat actionWithAction:rotate times:5];
	// CCRepeatForever用于包装其他的动作,指定无限次重复
    CCRepeatForever *repeat = [CCRepeatForever actionWithAction:sequence];
    [s runAction:repeat];
}

@end

H:/0925/04-消息调度(定时器)_Bullet.h
//
//  Bullet.h
//  04-消息调度(定时器)
//
//  Created by apple on 13-9-25.
//  Copyright (c) 2013年 itcast. All rights reserved.
//

#import "CCSprite.h"
 
@interface Bullet : CCSprite

// 速度(每秒挪动这个速度),子弹也可以有Y方向的速度,像魂斗罗里面的F子弹
@property (nonatomic, assign) CGPoint velocity;

@end

H:/0925/04-消息调度(定时器)_Bullet.m
//  Bullet.m
//  04-消息调度(定时器)
#import "Bullet.h"
#import "cocos2d.h"
@implementation Bullet
- (id)initWithTexture:(CCTexture2D *)texture rect:(CGRect)rect
{
    if (self = [super initWithTexture:texture rect:rect]) {
        // 默认就会调用update:方法
        [self scheduleUpdate];
        //[self schedule:@selector(update:)];
        
        // 设置消息调度的优先级(值越小,越先调用)
        // [self scheduleUpdateWithPriority:-1];
        
        // 取消消息调度,指定方法名
        // [self unschedule:<#(SEL)#>];
    }
    return self;
}
// 路程 = 速度 * 时间
// 有时候,该参数有用,delta 两次刷帧的时间间距,即1/60s
- (void)update:(ccTime)delta
{
    // 每次增加5的x值,子弹怎么走,子弹最清楚
    // self.position = ccpAdd(self.position, ccp(5, 0));
    // 距离=速度(包括X,Y方向) * 时间
    CGPoint distance = ccpMult(_velocity, delta);
    // 新位置=旧位置+该时间内移动的X,Y距离
    self.position = ccpAdd(self.position, distance);
}
@end

H:/0925/04-消息调度(定时器)_HelloWorldLayer.h
//
//  HelloWorldLayer.h
//  04-消息调度(定时器)
//
//  Created by apple on 13-9-25.
//  Copyright itcast 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

// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;

@end

H:/0925/04-消息调度(定时器)_HelloWorldLayer.m
//  HelloWorldLayer.m
//  04-消息调度(定时器)
//  Created by apple on 13-9-25.
//  Copyright itcast 2013年. All rights reserved.
// Import the interfaces
#import "HelloWorldLayer.h"
#import "Bullet.h"
#import "AppDelegate.h"
@implementation HelloWorldLayer
// 固定代码,创建包含特定图层的场景
+(CCScene *) scene
{
	CCScene *scene = [CCScene node];
	HelloWorldLayer *layer = [HelloWorldLayer node];
	[scene addChild: layer];
	return scene;
}
-(id) init
{
	if( (self=[super init]) ) {
		// 问导演要屏幕尺寸
        CGSize winSize = [CCDirector sharedDirector].winSize;
        // 通过图片创建一个精灵
        CCSprite *person = [CCSprite spriteWithFile:@"grossini.png"];
		// 给人添加一个tag,方便其他方法中使用
        person.tag = 10;
        person.position = ccp(winSize.width - 50, winSize.height * 0.5);
        [self addChild:person];
        // 让图层可以被点击
        self.touchEnabled = YES;
        
        // 开启消息调度,每隔一段时间调用一次update方法
        [self schedule:@selector(update)];
	}
	return self;
}
// 自定义方法,供schedule消息调度,调用,实质是计时器
- (void)update
{
    CCSprite *child = nil;
	// CCARRAY_FOREACH 宏定义
    CCARRAY_FOREACH(self.children, child)
    {
		// 前文设定person的tag是10,其他的都是子弹
        if (child.tag != 10) { 
            // 子弹往右边飞
            //CGPoint pos = child.position;
			//pos.x += 5;
			//child.position = pos;
            CCSprite *person = (CCSprite *)[self getChildByTag:10];
            if ( CGRectIntersectsRect(child.boundingBox, person.boundingBox) )
            {
                // 碰到了人,移除子弹removeFromParentAndCleanup
                [child removeFromParentAndCleanup:YES];
                // CCLOG(@"碰到了人");
            } else if ( !CGRectContainsRect(self.boundingBox, child.boundingBox) ) {
                // 到了屏幕外边,移除子弹removeFromParentAndCleanup
                [child removeFromParentAndCleanup:YES];
                // CCLOG(@"离开了屏幕");
            }
        }
    }
}
// Touches es复数,和UI中触摸的一模一样
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    // convertTouchToGL 将触摸对象转为OpenGL 坐标系的点
    CGPoint point = [[CCDirector sharedDirector] convertTouchToGL:touch];
    Bullet *bullet = [Bullet spriteWithFile:@"bullet.png"];
	// 点击屏幕哪儿,就在哪儿产生一个子弹对象
    bullet.position = point;
	// 设置子弹速度,每秒钟,移动X方向500,Y方向为-100~100,
	// 随机数:CCRANDOM_MINUS1_1()  随机-1~1
		    //CCRANDOM_0_1()  随机0~1
    bullet.velocity = ccp(500, CCRANDOM_MINUS1_1() * 100); 
    [self addChild:bullet];
}
@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值