在上一節我們講了精靈表的一些知識和使用Zwoptex對圖片進行了整合和產生plist檔案。這一節我們應用上一節的工具重建一對精靈表,對精靈進行操作。
1.建立工程
建立完工程後,如下:
2.載入檔案
分別載入以上4個精靈,利用zwoptex產生的plist和png檔案如下:
接下來把產生的plist和png匯入resources檔案中。
3.編程
在HelloWorld中的.m檔案的注釋掉裡面其他的代碼,重寫如下:
代碼解釋如下:
CGSize s = [[CCDirector sharedDirector] winSize];//擷取螢幕的尺寸
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"sprite.plist"];//載入我們產生的plist檔案到CCSpriteFrameCache的緩衝檔案中
//擷取精靈表中的第一張圖片載入在情境中,並設定他的位置
sprite1 = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"sprite_01.png"]];
sprite1.position = ccp( s.width/2-80, s.height/2);
[self addChild:sprite1];
//擷取精靈表中的第二張圖片載入在情境中,並設定他的位置
sprite2 = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"sprite_03.png"]];
sprite2.position = ccp( s.width/2+80, s.height/2);
[self addChild:sprite2];
//根據設定的時間更新頁面。調用updateSprite方法
[self schedule:@selector(updateSprite:) interval:0.3f];
當調用updateSprite方法實現小鳥眨眼睛的更新。
代碼的解釋如下:
static int sprite1FrameIndex = 0;//標誌位置為0
static int sprite2FrameIndex = 4;//標誌位置為4
-(void) updateSprite:(ccTime)dt
{
if (++ sprite1FrameIndex > 2) {
sprite1FrameIndex = 1;//進行迴圈。使精靈1不斷執行相同的過程
}
if (++ sprite2FrameIndex > 4) {
sprite2FrameIndex = 3;//進行迴圈。使精靈2不斷執行相同的過程
}
//更新的時候顯示其他的精靈圖片。
[sprite1 setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"sprite_%02d.png",sprite1FrameIndex]]];
[sprite2 setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"sprite_%02d.png",sprite2FrameIndex]]];
}
4.運行如
5.總結
這一節的重點在於如何對上一節產生的檔案進行讀取並做成動畫效果顯示,其中,CCSpriteFrameCache和setDisplayFrame這兩個方法較為重要,可以重點掌握一下,以便能夠熟練的應用在日常的遊戲開發項目中。
源碼在這裡下載:http://download.csdn.net/detail/qiaoshe/3707533