快速連結

2011年8月5日

利用cocos2D讓材質精靈顯示在畫面上

使用版本:Xcode 4, cocos2D 1.0.1

在cocos2D 0.99版後,已經讓CCSpriteBatchNode取代了CCSpriteSheet,快取與暫存更有優勢的樣子。
好啦其實我是半桶水,接下來就來拼拼湊湊cocos2D提供的template中我需要的語法來作出這個畫面吧:



首先開啓一個空白的cocos2D的template,然後你會發現很多東西,嗯,一開始看我也傻了(笑)。
HelloWorldLayer.m以及.h,這是未來的主要要CODE的地方

(看到沒有XIB檔案的我整個人要下跪了(欸))


我們要利用CCSpriteBatchNode做精靈的初始化,然後在觸動touch來取得位置生出房子精靈們~
話說要先準備一張圖哦~我在這裡把圖命名為house.png


先在.h檔案內寫下這兩行:

-(void)init_batch;
-(void)addSprite:(CGPoint)p;



然後到.m檔案內,我們要建立tag集,也就是做幫材質精靈做TAG~方便之後呼叫這個精靈時使用

enum {
 kTagTileMap = 1,
};


接著移動到-(id) init內:

if( (self=[super init])) {
        //支持觸摸
        self.isTouchEnabled = YES;
        [self init_batch];
}


然後在@end前建立function吧~
capacity表示你在畫面上要放上多少的圖,那這個容許量是多少~

-(void)init_batch{
    CCSpriteBatchNode *batch = [CCSpriteBatchNode batchNodeWithFile:@"house.png" capacity:150];
    [self addChild:batch z:0 tag:kTagTileMap];
}

-(void)addSprite:(CGPoint)p{
    CCSpriteBatchNode *batch = (CCSpriteBatchNode*) [self getChildByTag:kTagTileMap];
 
 //We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is
 //just randomly picking one of the images
 int idx = arc4random()%12;//因為橫排有十二列
 int idy = arc4random()%4;//因為直排有四列
 CCSprite *sprite = [CCSprite spriteWithBatchNode:batch rect:CGRectMake(32 * idx,32 * idy,32,32)]; //每格大小剛好是32X32
 [batch addChild:sprite];
 
 sprite.position = ccp( p.x, p.y);

}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CCLOG(@"touch");
 //Add a new body/atlas sprite at the touched location
 for( UITouch *touch in touches ) {
  CGPoint location = [touch locationInView: [touch view]];
  
  location = [[CCDirector sharedDirector] convertToGL: location];
  
  [self addSprite: location];
 }
}



以上就可以看到在模擬器上面,點擊螢幕就會出現圖(房子)了哦!

沒有留言:

張貼留言

歡迎大家留言提問,我會答的都會盡力回答!
如果太久沒出現回應就是我又忘記回來看留言了TAT