Cocos2d でスプライト シートをより適切に使用する方法を学ぶために、デモ アプリケーションを作成しようとしています。これまでのところ、スプライトの準備はすべて整いました。シートは見栄えがよく、コードも見栄えがしますが、スプライトが表示されません!
スプライトを含む Dice オブジェクトと、サイコロを画面にアニメーション化する前にランダムな面を選択する関数があります。あなたがそれらを転がしているようなものになっているはずです。
私が使用した操作の順序は次のとおりです。
- スプライト データの plist をフレーム キャッシュに追加します。
- スプライト シート バッチ ノードを作成する
- Dice オブジェクトを初期化し、ランダムな面を選択して、スプライト シートに追加します (バッチ ノード)。
- スプライト シート (バッチ ノード) をゲーム レイヤーに追加します。
プロジェクト全体へのリンクはこちらです。気軽に刺してください。
https://github.com/rnystrom/MartionDemo
上で説明した内容と、Dice オブジェクトの機能の抜粋を次に示します。
// Add spritesheet to the sprite cache
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"spritesheet.plist"];
self.spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"spritesheet.png"];
for (int i = 0; i < kNumDice; ++i) {
// Create Dice object
// CODE BELOW HAPPENS HERE AT initRandom
Dice* d = [[Dice alloc] initRandom];
// Add die to spritesheet
[self.spriteSheet addChild:d.sprite];
// Add Dice object to the array of rollable dice
[rollDiceArray addObject:d];
}
// Add spritesheet to the game layer
[self addChild:self.spriteSheet];
以下は、サイコロの初期化で何が起こるかの要約です (上記の initRandom を参照してください)。
// ... Sets up stuff like the # of frames, picking a random side of the die, etc ...
// Add each frame to the frames array
for(int i = 1; i <= numberFrames; i++) {
if (i < 10) {
[frames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"%@0%d.png", self.face, i]]];
}else{
[frames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"%@%d.png", self.face, i]]];
}
}
// Animation object with 0.04 seconds between each frame (~30fps)
CCAnimation *anim = [CCAnimation animationWithFrames:frames delay:0.04f];
// Update the sprite with the new frames
self.sprite = [CCSprite spriteWithSpriteFrameName:[NSString stringWithFormat:@"%@01.png", self.face]];
// Animate the sprite
[self.sprite runAction:[CCAnimate actionWithAnimation:anim restoreOriginalFrame:NO]];