1

我正在尝试编写一个演示应用程序来学习如何在 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]];
4

0 回答 0