在Swift中结束CAEmitterLayer的正确方法是什么?

时间:2018-07-10 18:23:18

标签: swift particles caemitterlayer caemittercell

我几乎在Swift中看到了连续发射器的示例,并且在Obj-C中找到了一个示例,方法是将发射器单元的birthRates设置为0.0,但它似乎不起作用,所以我必须做错了事。在我的示例中,我看到一条消息,将出生率设置为0十六倍,但是粒子继续不断流动。

@IBAction func particleBtnAction(_ sender: Any) {

    let emitter = CAEmitterLayer()
    emitter.emitterPosition = CGPoint(x: self.view.frame.size.width / 2, y: -10)
    emitter.emitterShape = kCAEmitterLayerLine
    emitter.emitterSize = CGSize(width: self.view.frame.size.width, height: 2.0)
    emitter.emitterCells = generateEmitterCells()
    self.view.layer.addSublayer(emitter)

    // perform selector after 1.5 seconds when particles start
    perform(#selector(endParticles), with: emitter, afterDelay: 1.5)

}

private func generateEmitterCells() -> [CAEmitterCell] {

    var cells:[CAEmitterCell] = [CAEmitterCell]()
    for index in 0..<16 {
        let cell = CAEmitterCell()
        cell.birthRate = 4.0
        cell.lifetime = 1.0
        cell.lifetimeRange = 0
        cell.velocity = 0.7
        cell.velocityRange = 0
        cell.emissionLongitude = CGFloat(Double.pi)
        cell.emissionRange = 0.5
        cell.spin = 3.5
        cell.spinRange = 0
        cell.scaleRange = 0.25
        cell.scale = 0.1
        cells.append(cell)
    }
    return cells
}

@objc func endParticles(emitterLayer:CAEmitterLayer) {

    for emitterCell in emitterLayer.emitterCells! {
        emitterCell.birthRate = 0.0
        print("birth rate set to 0")
    }

}

3 个答案:

答案 0 :(得分:4)

CAEmitterLayer的{​​{1}}设置为零将停止发出任何新的lifetime

emitterCells

答案 1 :(得分:0)

您可以使用键路径为每个单元格分配一个名称,并在它们之间循环,从而在您要更改每个单元格的属性时对其进行更改:

private func generateEmitterCells() -> [CAEmitterCell] {

    var cells:[CAEmitterCell] = [CAEmitterCell]()
    for index in 0..<16 {
        let cell = CAEmitterCell()
        cell.birthRate = 4.0
        cell.lifetime = 1.0
        cell.lifetimeRange = 0
        cell.velocity = 0.7
        cell.velocityRange = 0
        cell.emissionLongitude = CGFloat(Double.pi)
        cell.emissionRange = 0.5
        cell.spin = 3.5
        cell.spinRange = 0
        cell.scaleRange = 0.25
        cell.scale = 0.1
        cell.name = "cell\(index)" // cell name
        cells.append(cell)
    }
    return cells
}

@objc func endParticles(emitterLayer:CAEmitterLayer) {

    for i in 0..<(emitterLayer.emitterCells?.count ?? 0){

        emitterLayer.setValue(0.0, forKeyPath: "emitterCells.cell\(i).birthRate")
        print("birth rate set to 0")

    }

}

答案 2 :(得分:0)

当您想要endParticles时,您可以尝试设置isHidden属性

emitter.isHidden = true

但是请注意,所有细胞都将立即消失,无论它们何时被发射,或者其寿命如何。

另一种可能性是将所有与比例尺相关的属性设置为0,然后寿命和出生率就无关紧要,因为新发射的细胞将不可见。

cell.scaleSpeed = 0
cell.scaleRange = 0
cell.scale = 0