2017-09-16 11 views
0

Ich habe diese Funktion, die ich Blumen zu erzeugen bin mit Objekten an zufälligen Orten jede Sekunde:„attemped eine SKNode geben, die bereits einen Elternteil“ in Swift

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) 
     } 
    } 
} 

Ich bin eine neue Instanz für die Blumen zu schaffen jedes Mal wird die Funktion aufgerufen, aber aus irgendeinem Grund, wenn ich die Funktion wie unten nennen, es gibt mir den Fehler:

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

die spawnFlower() Funktion wird jede Sekunde aufgerufen. Es funktioniert beim ersten Aufruf und beim zweiten Absturz. Was mache ich falsch?

Antwort

0

Der Aufruf von addChild() muss sich außerhalb der for-Schleife bewegen, sodass nur einmal zum übergeordneten Element hinzugefügt wird.

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

Danke, das hat funktioniert. Ich musste auch die flowerArray.append (tempFlower) -Zeile in die if-Anweisung einfügen, da tooClose immer auf "true" gesetzt wurde. – 5AMWE5T

Verwandte Themen