1

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

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

}

我尝试在不同的地方获取日志,并意识到 getChildByTag 不能像我尝试使用它那样工作。

4

2 回答 2

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 部分代码在其中生成这样的精灵。您可以enum在 .m 中包含一个(在 @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);
}
.
.
.

希望这能激发你的创造力。现在有一些乐趣。

于 2012-01-18T06:17:51.807 回答
0

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

我将创建一个派生自 CCNode 的类

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

for(CCSprite *hurdle in [self children]) {
    // Do what you need to do
}
于 2012-01-18T15:17:15.783 回答