2017-09-16 55 views
0

我有這個功能,我使用生成花隨機的位置的物體每秒:「Attemped添加已經具有父SKNode」斯威夫特

func spawnFlower() { 
    //Create flower with random position 
    let tempFlower = Flower() 
    let height = UInt32(self.size.height/2) 
    let width = UInt32(self.size.width/2) 
    let randomPosition = CGPoint(x: Int(arc4random_uniform(width)), y: Int(arc4random_uniform(height))) 
    tempFlower.position = randomPosition 

    var tooClose = false 
    flowerArray.append(tempFlower) 

    // enumerate flowerArray 
    for flower in flowerArray { 

     // get the difference in position between the current node 
     // and each node in the array 
     let xPos = abs(flower.position.x - tempFlower.position.x) 
     let yPos = abs(flower.position.y - tempFlower.position.y) 

     // check if the spawn position is less than 10 for the x or y in relation 
     // to the current node in the array 
     if (xPos < 10) || (yPos < 10) { 
      tooClose = true 
     } 

     if tooClose == false { 
      //Spawn node 
      addChild(tempFlower) 
     } 
    } 
} 

我創造了花一個新的實例每一次函數被調用,但由於某種原因,當我調用該函數類似下面,它給我的錯誤:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent: 

的spawnFlower()函數被調用每一秒。它第一次被調用,第二次崩潰。我究竟做錯了什麼?

回答

0

addChild()調用需要移出for循環,因此tempFlower僅被添加到其父項中。

func spawnFlower() { 
    //Create flower with random position 
    let tempFlower = Flower() 
    let height = UInt32(self.size.height/2) 
    let width = UInt32(self.size.width/2) 
    let randomPosition = CGPoint(x: Int(arc4random_uniform(width)), y: Int(arc4random_uniform(height))) 
    tempFlower.position = randomPosition 

    var tooClose = false 
    flowerArray.append(tempFlower) 

    // enumerate flowerArray 
    for flower in flowerArray { 

     // get the difference in position between the current node 
     // and each node in the array 
     let xPos = abs(flower.position.x - tempFlower.position.x) 
     let yPos = abs(flower.position.y - tempFlower.position.y) 

     // check if the spawn position is less than 10 for the x or y in relation 
     // to the current node in the array 
     if (xPos < 10) || (yPos < 10) { 
      tooClose = true 
     } 
    } 

    if tooClose == false { 
     // Spawn node 
     addChild(tempFlower) 
    } 
} 
+0

謝謝,這工作。最後,我還不得不在if語句中放入flowerArray.append(tempFlower)行,因爲每次都將CloseClose設置爲true。 – 5AMWE5T