添加和访问CCSprites

时间:2012-01-18 06:03:09

标签: ios cocos2d-iphone ccsprite

我在插入多个相同精灵的子节点并访问它(或在运行时为它们设置位置)时遇到问题。请建议任何合适的方法,最好指出我的错误。这是我的方法。

//In the Init Method...

//int i is defined in the start.

    for (i = 1; i < 4; i++)

    {

        hurdle = [CCSprite spriteWithFile:@"hurdle1.png"];

        [self addChild:hurdle z:i tag:i];

        hurdle.position = CGPointMake(150 * i, 0);

    }

它将所有精灵传播到画布上。然后在一些“UPDATE函数”中我称之为。

hurdle.position = CGPointMake(hurdle.position.x - 5, 10);

if (hurdle.position.x <= -5) {
    hurdle.position = ccp(480, 10);
}

它有效,但正如预期的那样,只有一个实例水平移动。我想要移动所有实例,所以我试图使用它....

for (i = 1; i < 4; i++){

   [hurdle getChildByTag:i].position = CGPointMake(hurdle.position.x - 5, 10);

//OR
   [hurdle getChildByTag:i].position = CGPointMake([hurdle getChildByTag:i].position.x - 5, 10);

}

我尝试在各个地方获取LOG并意识到getChildByTag不能像我尝试使用它那样工作。

2 个答案:

答案 0 :(得分:2)

问题出在最后一段代码中。您应该在for循环中对每个CCSprite进行本地引用。

由于您已将精灵添加到self,因此您将检索它们为self

的子项
for (i = 1; i < 4; i++){
   CCSprite * enumHurdle = [self getChildByTag:i];
   enumHurdle.position = CGPointMake(enumHurdle.position.x - 5, 10);
}

如果您在同一场景中以这种方式创建任何其他精灵,请务必小心。为任何两个精灵提供相同的标签是不好的设计。

编辑避免重复标记。

如果你知道你将拥有多少精灵。使用标签枚举并按名称引用精灵。

如果没有,知道有多少组并限制组的大小可以使其成为可管理的。

即 假设您有3个代码部分,您可以生成这样的精灵。您可以在.m中包含enum(在@implementation行下)并在其中添加限制

// Choose names that describe the groups of sprites
enum { kGroupOne = 0, // limiting the size of each group to 100 
    kGroupTwo = 100, // (besides the last group, but that is not important)
    kGroupThree = 200, 
};

然后当您创建每个组

// group 1
for (i = kGroupOne; i < 4; i++){
   // set up code here
}

// group 2 
// g2_size is made up, insert whatever you want
for (i = kGroupTwo; i < g2_size; i++) {
   // set up code here
}
.
.
.

然后分组检索

for (i = kGroupOne; i < 4; i++){
   CCSprite * enumHurdle = [self getChildByTag:i];
   enumHurdle.position = CGPointMake(enumHurdle.position.x - 5, 10);
}
.
.
.

希望这能激发你的创造力。现在玩得开心。

答案 1 :(得分:0)

我经常做的事情是类似的组对象,我希望以类似的方式将它们添加到CCNode并将该CCNode添加到图层。

我会创建一个派生自CCNode

的类

然后我可以将所有逻辑放在该节点中,然后通过[self children]

访问
for(CCSprite *hurdle in [self children]) {
    // Do what you need to do
}