Director, Scenes, and Layers

本文介绍Cocos2d中CCDirector类的主要职责,包括管理游戏场景、配置细节及OpenGL视图等。同时讲解了如何使用CCScene、CCLayer创建游戏场景,并通过CCDirector进行场景切换。此外,还探讨了触控、加速度计和键盘事件的处理方式。

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

The Director    

[CCDirector sharedDirector]

The CCDirector class stores global configuration settings for cocos2d and also manages the cocos2d scenes. The major responsibilities of the CCDirector class include the following:

1. Providing access to the currently running scene
2. Running, replacing, pushing, and popping scenes
3. Providing access to cocos2d configuration details
4. Providing access to cocos2d’s OpenGL view and window Pausing, resuming, and ending the game
5. Converting UIKit and OpenGL coordinates
6. Determining how game state is updated

// Try CADisplayLink director first.

// If CADisplayLink is not available (iOS < 3.1) fall back to NSTimer director. 

if ( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
	[CCDirector setDirectorType:kCCDirectorTypeDefault];

You can set four Director types:
kCCDirectorTypeDisplayLink (fastest; requires iOS 3.1 or newer)
kCCDirectorTypeNSTimer (slowest)
kCCDirectorTypeThreadMainLoop (fast but has issues with UIKit views) 
kCCDirectorTypeMainLoop (fast but has issues with UIKit views) 


CCScene   

But the CCDirector requires a CCScene-derived class to be able to change the currently active scene graph via the CCDirector runWithScene, replaceScene, and pushScene methods. You can also wrap a CCScene class into a class derived from CCSceneTransition in order to animate the transition between a currently running scene and the new scene.


Normally the only children of a CCScene are those derived from CCLayer, which in turn contain the individual game objects .

CCScene *scene = [CCScene node]; 
CCLayer* layer = [HelloWorld node]; 
[scene addChild:layer]; 

// only use this to run the very first scene
[[CCDirector sharedDirector] runWithScene:[HelloWorld scene]]; 

CCScene* scene = [HelloWorld scene];
CCTransitionScene * tran = [CCTransitionShrinkGrow transitionWithDuration:2 scene:scene]; 
[[CCDirector sharedDirector] replaceScene:tran]; 


Scenes and Memory    

Keep in mind that when you replace one scene with another, the new scene is loaded into memory before the old scene’s memory is freed. 


One thing you should never do is add a node as a child to the scene graph and then retain it yourself for some other purpose. Use cocos2d’s methods to access node objects instead, or at the very least keep a weak reference to the pointer instead of retaining it. As long as you let cocos2d worry about managing the memory of nodes, you should be fine.

Pushing and Popping Scenes    

[[Director shareDirector] pushScene] : Don’t removing old scece from memory. Making changing scenes faster.
[[Director shareDirector] popScene]

Showcase:

1. one is if you have one common scene that’s used in many places, such as the Settings screen where you can change music and sound volume.  

2. pushScene and popScene are very useful is if you want to retain the state of the initial scene without having to revert to saving and loading that scene’s state.  

CAUTION: You can animate the pushScene call only with CCSceneTransition classes and not popScene. This is a drawback of pushing and popping scenes that you should be aware of.


CCTransitionScene   

You can use a CCTransitionScene with replaceScene and pushScene, but as I said earlier, you can’t use a transition with popScene.


CCLayer   


Sometimes you need more than one layer in your scene.     

In addition, all objects of the same layer will be either in front of or behind objects of another layer, depending on the z-order of the layers.


Receiving Touch Events    


The CCLayer class is designed to receive touch input but only if you explicitly enable it. To enable receiving touch events, set the property isTouchEnabled to YES:

self.isTouchEnabled = YES; 
       
This is called when a finger just begins touching the screen: 
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
          
 This is called whenever the finger moves on the screen:
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
          
 This is called when a finger is lifted off the screen:
-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
          
This is called to cancel a touch:
-(void) ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event 

Convert location to openGL coordinates:

-(CGPoint) locationFromTouches:(NSSet *)touches 
{   
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView: [touch view]]; 
return [[CCDirector sharedDirector] convertToGL:touchLocation];   
}

To keep track of multitouch locations, you have to keep track of each touch individually.

Targeted touch handlers :

Cocos2d also supports targeted touch handlers. The difference is that targeted touches receive only one touch at a time, in comparison to the UIResponder touch events that always receive a set of touches.  

To enable the targeted touch handler, add the following method to your layer’s class:

-(void) registerWithTouchDispatcher 
{
   
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self 
priority:INT_MIN+1
swallowsTouches:YES];
} 
         
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {} 
-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {} 
-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {}
 -(void) ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event {}


Receiving Accelerometer Events    


self.isAccelerometerEnabled = YES;

Once more, there’s a specific method to be added to the layer that receives the accelerometer events:

-(void) accelerometer:(UIAccelerometer *)accelerometer   didAccelerate:(UIAcceleration *)acceleration
{
CCLOG(@"acceleration: x:%f / y:%f / z:%f", acceleration.x, acceleration.y, acceleration.z); 
}  


Receiving Keyboard Events    

self.isKeyboardEnabled = YES;

The callback methods to receive keyboard events are defined in the CCKeyboardEventDelegate protocol as follows:

-(BOOL) ccKeyDown:(NSEvent*)event {
 CCLOG(@"key pressed: %@", [event characters]); 
}
      
-(BOOL) ccKeyUp:(NSEvent*)event {      
CCLOG(@"key released: %@", [event characters]); 
}   
     
-(BOOL) ccFlagsChanged:(NSEvent*)event {
 CCLOG(@"flags changed: %@", [event characters]); 
}


Receiving Mouse Events     


self.isMouseEnabled = YES;
CGPoint mousePos = [[CCDirector sharedDirector] convertEventToGL:event];     

CCSprite   

CCSprite uses an image to display the sprite on-screen.

CCSprite* sprite = [CCSprite spriteWithFile:@”Default.png”]; 
[self addChild:sprite]; 

The texture is centered on the sprite’s position.  


Anchor Points Demystified    

Every node has an anchor point. By default, the anchorPoint property is at 0.5,0.5, or, in other words, at the center of the texture.
如果Anchor point设为(0, 0), 那么texture的位置就是左下角点.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值