用Swift写CAEmitterLayer,如何让粒子停止发射呢?

1.我无论如何都无法让粒子停止发射。主要问题在touchesEnded()这个方法里,为什么cell.birthRate = 0这个不能让这个粒子停止发射呢?谢谢!

2.代码如下

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        createParticles()

    }
    
    var touchPostion = CGPoint.zero {
        didSet{
            emitter.emitterPosition = touchPostion
        }
    }
    
    var emitter = CAEmitterLayer()
    var cell = CAEmitterCell()
    
    //产生粒子
    func createParticles() {
        
        let view = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        view.backgroundColor = UIColor.black
        
        self.view.addSubview(view)
        
        emitter.emitterShape = kCAEmitterLayerLine
        emitter.emitterSize = CGSize(width: 1, height: 1)
        
        
        let flake = makeEmitterCell()
        emitter.emitterCells = [flake]
        view.layer.addSublayer(emitter)
        print("began")
    }
    
    //开始触摸
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if (touches.first != nil) {
            touchPostion.x = (touches.first?.location(in: self.view).x)!
            touchPostion.y = (touches.first?.location(in: self.view).y)!
        }
        print(touchPostion.x , "," , touchPostion.y)
        cell.birthRate = 50.0
    }
    
    //触摸移动
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if (touches.first != nil) {
            touchPostion.x = (touches.first?.location(in: self.view).x)!
            touchPostion.y = (touches.first?.location(in: self.view).y)!
        }
    }
    `
    //结束触摸
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        //不再产生粒子
        cell.birthRate = 0.0
        print("ended")
        
    }
    `
    //关于粒子
    func makeEmitterCell() -> CAEmitterCell {
        
        cell.contentsScale = 2
        cell.lifetime = 3.0
        cell.velocity = -40
        cell.xAcceleration = 20
        cell.yAcceleration = 50
        cell.zAcceleration = 30
        cell.velocityRange = 20
        cell.emissionLongitude = CGFloat.pi
        cell.emissionRange = CGFloat.pi / 4
        cell.scaleRange = 0.0
        cell.alphaSpeed = -0.4
        
        cell.contents = UIImage(named:"Drop")?.cgImage
        print("emitting")
        
        return cell
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
    }
}
阅读 4.4k
1 个回答

设置 emitter.birthRate = 0 才能停止粒子发射

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题