我有这个功能,我每秒都会在随机位置生成Flower对象:
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)
}
}
}
每次调用函数时,我都会为flower创建一个新实例,但出于某种原因,当我调用下面的函数时,它会给出错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent:
每秒调用spawnFlower()函数。它在第一次调用时工作,第二次崩溃。我做错了什么?
答案 0 :(得分: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)
}
}