【问题标题】:"Attemped to add a SKNode which already has a parent" in Swift在 Swift 中“尝试添加一个已经有父节点的 SKNode”
【发布时间】:2017-09-16 22:10:36
【问题描述】:

我有这个函数用来每秒在随机位置生成 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)
        }
    }
}

每次调用该函数时,我都会为花创建一个新实例,但由于某种原因,当我调用如下函数时,它给了我错误:

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

spawnFlower() 函数每秒调用一次。它在第一次调用时工作,第二次崩溃。我做错了什么?

【问题讨论】:

    标签: arrays swift spawn sknode


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这行得通。我最终不得不将flowerArray.append(tempFlower) 行放在if 语句中,因为每次都将tooClose 设置为true。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多