【问题标题】:Adding and accessing CCSprites添加和访问 CCSprite
【发布时间】:2012-01-18 06:03:09
【问题描述】:

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

//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);

    }

它将所有精灵散布在画布上。然后在一些“更新函数”中我调用它。

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 无法像我尝试使用它那样工作。

【问题讨论】:

    标签: ios cocos2d-iphone ccsprite


    【解决方案1】:

    问题出在最后一段代码中。您应该在 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);
    }
    .
    .
    .
    

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

    【讨论】:

    • 我应该将 enumHurdle 声明为什么? CCSprite?
    • 非常感谢您的帮助。但是现在我对添加更多精灵一无所知,但想避免共享相同的标签:D
    • 再次感谢。我使用不同的 FOR LOOPS 开始和结束于不同的值,如 (1 - 4) 和 (5-8) 但我使用该 FOR 循环变量作为它们距离的乘数(oooops):D 我肯定会仍然是核心问题。到目前为止,非常感谢您的帮助有人建议我添加一个虚拟精灵并制作该虚拟精灵的障碍孩子。但这也是迄今为止未解之谜。
    【解决方案2】:

    我经常做的事情是将类似类型的对象分组,我想通过将它们添加到 CCNode 并将该 CCNode 添加到层来以类似的方式对其进行操作。

    我会创建一个从 CCNode 派生的类

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多