我用的是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类中。