2012-01-17 64 views
0

我學習的Cocos2D和構建應用的時候,在一端有雪碧,我需要通過它的另一邊,並與同我從屏幕中移除精靈,並在一段時間後,我在顯示相同。如何用圖像數組cocos2d更改精靈圖像?

現在我有我的應用程序圖像的文件夾,我需要每次都以隨機順序從同一文件夾中加載不同的圖像和維護日誌,這些照片不會一次又一次地重複。我能夠從文件夾中加載圖像有:

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath]; 
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bundleRoot error:nil]; 
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"]]; 

現在我怎麼會叫這個數組,每次顯示不同的圖像,並且還保持了日誌圖像沒有得到重複。我已經通過鏈接,如thisthis,但在vail。任何線索都會非常有幫助。感謝您提前的幫助。

回答

1

做到這一點的最好方法是創建一個spriteSheet。首先你可以得到http://zwoptexapp.com/,它的免費,你可以創建你的spritesheet使用科科斯(在出口商請確保你選擇cocos2d創建適當的plist)

你想打包所有圖像在1大紋理這樣你就可以用plist中它添加到您的項目(zwoptex將創建兩個你)

那麼你就可以

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"your_plist"]; 

切換紋理加載紋理操作慢,所以有在所有圖像在完成對spri的紋理更改後,相同的紋理將提升openGL的性能TE是很容易

[yourSprite setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"FRAME_NAME"]]; 

其中FRAME_NAME是在plist中框架的名稱(您可以通過選擇裏面的Xcode plist中看到它。

以隨機的方式循環,而不必重複圖片... (我會直接在這裏寫一些僞代碼,讓我做inits類的聲明和內聯實現:)內)

//WARNING THIS IS PSEUDO CODE :) 

    @interface Randomizer { 
     //an array of NSStrings containing all you images names  
     NSMutableArray *allImagesFrameNames = [NSMutableArray arrayWithCapacity:NUM_FRAMES]; 
CCSprite *sprite = alloc init 
    } 

-(void) resetAllFrames { 
[allImagesFrameNames removeAllobjects]; 

[allImagesFrameName addObject:@"FIRST_IMAGE"]; 
[allImagesFrameName addObject:@"SECOND_IMAGE"]; //add all your images 
} 

@end

,並顯示一個隨機幀:

-(void) display a randomImage { 
//if the array is empty, all images are already been randomly displayed, so we reset the array 
if([allImagesFrameName count] == 0) 
[self resetAllFrames]; 

//we choose a random index 
int randomIndex = arc4random %[allImagesFrameName count]; 
//we get the frame name at that index 
NSString *imageFrameName = [allImagesFrameNames objectAtIndex:randomIndex]; 

//and we display the frame 
[sprite setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:imageFrameName]]; 

[allImagesFrameNames removeObjectAtIndex:randomIndex]; 

} 
+0

感謝您Ultrakorne .. :)讓我實現了相同的回來給你。我想這對我很有用。 – Sarah 2012-01-18 09:44:37