2016-04-05 47 views
0

確定,所以我有這樣的代碼,其中產卵的位置被放入一個數組,然後所述位置之一被隨機選出與此代碼:以陣列選項出一個週期

let randx = spawnLocations[Int(arc4random_uniform(UInt32(spawnLocations.count)))] 
      obstacle.position = CGPoint(x: randx, y: 0) 

對象產卵代碼:

var spawnLocations:[CGFloat] = [] 

func getObjectSpawnLocation() { 

//Create 5 possible spawn locations 
let numberOfNodes = 5 

    // Spacing between nodes will change if: 1) number of nodes is changed, 2) screen width is changed, 3) node's size is changed. 
    for i in 0...numberOfNodes - 1 { 

     // spacing used to space out the nodes according to frame (which changes with screen width) 
     var xPosition = (frame.maxX /*- thePlayer.size.width*/)/CGFloat((numberOfNodes - 1)) * CGFloat(i) 

     //add a half of a player's width because node's anchor point is (0.5, 0.5) by default 
     xPosition += thePlayer.size.width/2 

     //I have no idea what this does but it works. 
     xPosition -= frame.maxX/1.6 
     spawnLocations.append(xPosition) 

    } 
() 
} 

但是我有一個問題,因爲有時比賽會生成類似下面的圖片中的對象,並沒有任何進一步的讓我的球員提前沒有他們死去,所以我的問題是:

無論如何,我可以阻止它做到這一點?

也許會暫時從數組中取出一個產卵位置?

我還應該注意到,每個物體(頭骨)都是一個接一個地並非全部產生,並且頭骨可以在5個水平位置中的任何一個處產生。

enter image description here

+0

我會有任何數量的障礙可以設置x位置。將這些數據存儲在一個數組中,並確保除了一個之外的所有數據都存在..這會留下一個空白 – hamobi

+0

您需要設置某種「路徑查找」來確保玩家能夠通過差距,比如從頂部開始,沿着每個節點走下去,如果開始到達終點,就會出現問題,修復它 – Knight0fDragon

回答

0

的玩家只能被困在頭骨和屏幕的邊緣之間。你應該跟蹤您是否正在播放或不是「楔入」,例如:

//Keep instance variables to track your current state 
BOOL lineFromEdge; //YES if you're currently drawing a "line" of skulls from an edge 
BOOL leftEdge; //YES if the line originates from the left edge, NO if from the right 
int previousIndex; 

然後你確定值,如下所示:

- (int) randomIndex { 

    int randIndex = Int(arc4random_uniform(UInt32(spawnLocations.count))); 

    // This expression tells you if your current index is at an edge 
    if (randIndex == 0 || randIndex == (spawnLocations.count - 1)) { 
     lineFromEdge = YES; 
     leftEdge = randIndex == 0; 
    } 

    //Check if you left a gap 
    BOOL didLeaveGap = abs(randIndex - previousIndex) > 1 
    if (didLeaveGap) lineFromEdge = NO; 

    if ((lineFromEdge && leftEdge && randomIndex == spawnLocations.count) || 
     (lineFromEdge && !leftEdge && randomIndex == 0)) { 

     //You have drawn a line from one edge to the other without leaving a gap; 
     //Calculate another index and perform the same checks again 
     return [self randomIndex]; 

    } 

    //Your index is valid 
    previousIndex = randIndex; 
    return randIndex; 
} 

注:您的算法必須返回0spawnLocations.count作爲這個工作的第一個索引。否則你的頭骨可能會從中心開始,但仍然沒有意識到它會讓玩家陷入困境。