cocos2d入门教程3:cocos2d运行机理

本文介绍使用 Cocos2d 2.0 版本为 iOS 平台创建基本游戏项目的步骤。从 AppDelegate 类配置 CCDirector 开始,通过 IntroLayer 类实现启动界面,并展示如何切换场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我用的是cocos2d 2.0版的,安装好模板以后新建一个工程cocos2d ios工程。运行发现它已经提供了一个可运行出来的简单程序,在界面上

显示hello world标签,然后有一个menu,两个menu item。工程里有3个类,AppDelegate类,Layer类和IntroLayer类。

AppDelegate类最重要的是包含了一个CCDirectorIOS类对象,在application:didFinishLaunchingWithOptions:方法用调用

CCDirector类的sharedDirector方法产生一个对象,查看sharedDirector方法会发现用这个方法产生的对象是单例的。

director_ = (CCDirectorIOS*) [CCDirector sharedDirector];

然后对这个导演进行设置。导演就是以后我们要用到管理各个scene的对象,它支配着程序应用哪个scene。

对导演设置完以后,调用IntroLayer的scene方法,

[director_ pushScene: [IntroLayer scene]]; 

进入到IntroLayer类中来对IntroLayer初始化。

+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	IntroLayer *layer = [IntroLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}


IntroLayer就是程序启动后第一个出现

的启动界面。去的scene,初始化layer,把Introlayer加到scene中进行显示。另外再加入到scene中后在CCScene类中调用

【child onEnter】方法,这样Introlayer的onEnter方法被调用从而完成初始化。绘出一个精灵,然后延迟一秒以后把Layer推入

导演管理的栈中,从而显示Layer对象,

-(void) onEnter
{
	[super onEnter];

	// ask director for the 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);

	// add the label as a child to this Layer
	[self addChild: background];
	
	// In one second transition to the new scene
	[self scheduleOnce:@selector(makeTransition:) delay:1];
}
把layer对象推入导演栈中


-(void) makeTransition:(ccTime)dt
{
	[[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:1.0 scene:[HelloWorldLayer scene] withColor:ccWHITE]];
}

我们以后的大多数操作都会在layer类中。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值