arrays - swift 中的 "Attemped to add a SKNode which already has a parent"

标签 arrays swift spawn sknode

我有这个函数,我用它每秒在随机位置生成 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() 函数每秒调用一次。第一次调用时它有效,第二次调用时它崩溃了。我做错了什么?

最佳答案

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

关于arrays - swift 中的 "Attemped to add a SKNode which already has a parent",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46258881/

相关文章:

c++ - std::array 的内联初始化有什么问题?

ios - 当已选择 selectedIndex 时,返回代码中选项卡栏 Controller 的原始 View

node.js - Node 生成标准输出未定义

node.js - 如何模拟 Node.js child_process spawn 函数?

c++ - 按字母顺序对c字符串数组进行排序

c# - new[] 和 new string[] 有什么区别?

javascript - jQuery 合并多个 javascript 数组值

ios - 如果设置角半径则不会应用阴影

ios - 联系人框架在需要时不请求访问

javascript - "Close"spawn() 函数的回调在 grunt 插件中不起作用