2012-01-18 66 views
1

我在插入同一精靈的多個子項並訪問它(或在運行時爲它們設置位置)時遇到問題。請提醒任何合適的方法,最好指出我的錯誤。這是我的方法。添加和訪問CCSprites

//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不工作我想的方式用它。

回答

2

問題出在最後一塊代碼中。您應該在for循環中爲每個CCSprite創建一個本地引用。

既然你添加的精靈到self,你會找回它們爲self

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

孩子要小心,如果您創建的任何其他精靈這種方式在同一場景中。給任何兩個精靈設置相同的標籤是一個糟糕的設計。

關於避免重複標籤的編輯。

如果你知道你會有多少個精靈。使用標籤枚舉並通過名稱引用精靈。

如果不是,知道有多少組,並限制組的大小可以使其可管理。

ie 說你有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); 
} 
. 
. 
. 

希望能激發你的創造力。現在有一些樂趣。

+0

我應該聲明enumHurdle作爲一類? CCSprite? – 2012-01-18 06:35:20

+0

@ToughGuy這是正確的。謝謝,我會編輯它。 – 2012-01-18 06:44:48

+0

非常感謝您的幫助。但是現在我對加入更多精靈毫無頭緒,但是想要避免共享相同的標籤:D – 2012-01-18 07:05:34

0

我經常做的事情就是我想要以類似的方式加入CCNode並將該CCNode添加到該圖層的同類組對象。

我會創建一個從CCNode

得出這樣我就可以把我所有的邏輯節點和接入然後通過[自兒童]

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