2012-04-13 87 views
0

我正在開發我的第一個cocos2d遊戲。它會有一個循環的背景,三個不同的層次,都以不同的速度循環。循環的速度將根據用戶輸入而改變。cocos2d循環背景iPhone

這裏是我正在做這樣

-(void) update: (ccTime) dt 
{ 
for (CCSprite *bckgrnd in backgroundArray){ 
    switch (bckgrnd.tag) { 
     case 0: 
      bckgrnd.position = ccp(bckgrnd.position.x - speed * .30, bckgrnd.position.y); 
      break; 
     case 1: 
      bckgrnd.position = ccp(bckgrnd.position.x - speed * .80, bckgrnd.position.y); 
      break; 
     case 2: 
      bckgrnd.position = ccp(bckgrnd.position.x - speed * .50, bckgrnd.position.y); 
      break; 

     default: 
      break; 
    } 
    if (bckgrnd.position.x <= -kBacWidth) { 
     CGPoint greatestPosition = CGPointMake(0, 0); 
     for (CCSprite *sprt in backgroundArray){ 
      if (sprt.tag == bckgrnd.tag && sprt.position.x > greatestPosition.x) { 
       greatestPosition = CGPointMake(sprt.position.x, sprt.position.y); 
      } 
     } 

     bckgrnd.position = ccp(greatestPosition.x + kBacWidth, bckgrnd.position.y); 
    } 
} 
} 

這工作,但有兩個問題。首先它會在第二次循環後創建一個間隙,然後間隙停留在那裏。另一個問題是背景的不同部分似乎在向左移過屏幕時「擺動」。這會導致單獨的子畫面有時可能被像素覆蓋。我不能擁有。我哪裏錯了?提前致謝!

+0

爲什麼你有第二個循環?是不是sprt,通過條件「sprt.tag == bckgrnd.tag」與bckgrnd相同...你已經? – 2012-04-13 15:53:13

回答

0

我已經實現了垂直滾動射擊遊戲的ParallaxBackground,這裏是我的更新方法。我希望它確實有助於激勵你,因爲我在開始時也有缺口問題。

Te speedFactors是一組浮點對象,它決定了每個背景條紋的速度。我將numStripes乘以2,因爲我有一個頂部和底部條紋(圖像分成兩半),所以我可以在它們從視覺範圍外出時重新定位它們(​​條件:if(pos.y < -screenSize.height))。

精靈會作爲子類添加到類中,但如果您喜歡或者使用backgroundArray,也可以使用CCSpriteBatch。

-(void) update:(ccTime)delta 
{ 
    CCSprite* sprite; 
    int factorIndex=0; 
    for (int i=0; i<(numStripes*2); i++) { 

     sprite = (CCSprite*)[self getChildByTag:firstParallaxSpriteTag+i]; 

     NSNumber* factor = [speedFactors objectAtIndex:factorIndex]; 

     CGPoint pos = sprite.position; 
     pos.y -= scrollSpeed * [factor floatValue];; 

     // Reposition stripes when they're out of bounds 
     if (pos.y < -screenSize.height) 
     { 
      pos.y += (screenSize.height * 2) - 2; 
     } 
     sprite.position = pos; 
     factorIndex++; 
     if(factorIndex>=numStripes){ 
      factorIndex=0; 
     } 
    } 
} 

希望這個幫助,請不要猶豫,通過評論要求進一步的問題。 PS:爲了記錄,我的方法和類是從ShootEmUp示例this book中ParallaxBackground類的修改。你可以在鏈接中找到源代碼,我建議你也購買這本書。

PPS:爲了避免1像素的差距,您需要在重新定位精靈時將其刪除,爲避免背景精靈的間隙,您需要分配背景精靈的兩個實例並在屏幕上交替顯示它們(當一個是從你重新定位它的視覺範圍出發 - 在屏幕的頂部或側面,在你的案例側 - ),然後你繼續移動兩個背景精靈..如果你看到我的代碼或甚至更多的PrallaxBackground書中的例子你會明白的。