if语句将所有语句组合成一个if语句

时间:2011-01-24 21:12:54

标签: iphone if-statement cocos2d-iphone grouping sprite

如何创建一个if语句,将所有语句组合成一个if语句,此时我已经有20个或者某个if语句不是很有效,所以我想知道是否有办法对精灵进行分组因此,如果我的任何精灵从屏幕顶部移开,它们会重新出现在底部,反之亦然。

此刻我已经拥有了这个; yellow1,2,3 ... 是精灵

if (yellow1.position.y-33>=320) {
  yellow1.position = ccp(yellow1.position.x,33);
}
if (yellow1.position.y+33<=0) {
  yellow1.position = ccp(yellow1.position.x,287);
}
if (yellow2.position.y-33>=320) {
  yellow2.position = ccp(yellow2.position.x,33);
}
if (yellow2.position.y+33<=0) {
  yellow2.position = ccp(yellow2.position.x,287);
}
if (yellow3.position.y-33>=320) {
  yellow3.position = ccp(yellow3.position.x,33);
}
if (yellow3.position.y+33<=0) {
  yellow3.position = ccp(yellow3.position.x,287);
}
if (yellow4.position.y-33>=320) {
  yellow4.position = ccp(yellow4.position.x,33);
}
if (yellow4.position.y+33<=0) {
  yellow4.position = ccp(yellow4.position.x,287);
}
if (yellow5.position.y-33>=320) {
  yellow5.position = ccp(yellow5.position.x,33);
}
if (yellow5.position.y+33<=0) {
  yellow5.position = ccp(yellow5.position.x,287);
}
if (yellow6.position.y-33>=320) {
  yellow6.position = ccp(yellow6.position.x,33);
}
if (yellow6.position.y+33<=0) {
  yellow6.position = ccp(yellow6.position.x,287);
}
if (yellow7.position.y-33>=320) {
  yellow7.position = ccp(yellow7.position.x,33);
}
if (yellow7.position.y+33<=0) {
  yellow7.position = ccp(yellow7.position.x,287);
}
if (yellow8.position.y-33>=320) {
  yellow8.position = ccp(yellow8.position.x,33);
}
if (yellow8.position.y+33<=0) {
  yellow8.position = ccp(yellow8.position.x,287);
}

这是我到目前为止的循环:

for (int i=0;i<16 ; i++) {
    if (((CCSprite *)[c1array objectAtIndex:i]).position.y-((CCSprite *)[c1array objectAtIndex:i]).contentSize.height>320) {
        ((CCSprite *)[c1array objectAtIndex:i]).position = ccp(((CCSprite *)[c1array objectAtIndex:i]).position.x,37);
    }
    if (((CCSprite *)[c1array objectAtIndex:i]).position.y+((CCSprite *)[c1array objectAtIndex:i]).contentSize.height<0) {
        ((CCSprite *)[c1array objectAtIndex:i]).position = ccp(((CCSprite *)[c1array objectAtIndex:i]).position.x,253);
    }
}

2 个答案:

答案 0 :(得分:4)

你想要的是一个循环。但首先,您需要将数据结构化为顺序数据结构,例如数组。然后,您将循环遍历数组中的每个元素。

我不熟悉iPhone编程,但这里是一般的伪代码:

// Create the list
const int SPRITE_COUNT = 8;
Sprite[] sprites = new Sprite[SPRITE_COUNT];
for(int i = 0; i < SPRITE_COUNT; ++i)
    sprites[i] = new Sprite();

// Later, check for sprites outside
for(int i = 0; i < SPRITE_COUNT; ++i)
{
    if ((sprites[i].position.y + 33) <= 0)
        ccp(sprite.position.x, 287);
    if ((sprites[i].position.y - 33) >= 320)
        ccp(sprite.position.x, 33);
}

答案 1 :(得分:0)

你可以把你的精灵放在一个arraylist中,并遍历列表。这意味着您运行相同数量的代码,但让运行时执行其擅长的功能,并且您的代码将更加整洁。