两个对象之间的快速碰撞检测

时间:2019-01-10 17:35:07

标签: ios swift uikit

感到非常沮丧,并被告知要使用Stack Overflow寻求帮助!

这是我的问题:飞机与鸟相交后,我的分数无法降低!

func behaviorFunctions() {
    dynamicItemBehavior = UIDynamicItemBehavior(items: [bird1, plane1])
    collisionBehavior = UICollisionBehavior(items: [bird1, plane1])
    collisionBehavior.translatesReferenceBoundsIntoBoundary = true
    collisionBehavior.addBoundary(withIdentifier: "plane1" as NSCopying, for: UIBezierPath(rect: plane1.frame))
        collisionBehavior.addBoundary(withIdentifier: "bird1" as NSCopying, for: UIBezierPath(rect: bird1.frame));        animator.addBehavior(dynamicItemBehavior!)
    animator.addBehavior(collisionBehavior)


    collisionBehavior.action = {
        for _ in self.imageArrayBird!{
            if(self.plane1.frame.intersects(self.bird1.frame)){
                self.score = self.score - 50
            }
        }
    }
    }

这是什么问题?我该如何解决?

在此先感谢您的回答!

1 个答案:

答案 0 :(得分:0)

我不知道self.imageArrayBird来自哪里。如果您将其注释掉,则以下设置可以像魔术一样改变分数。

class MyViewController : UIViewController {
var animator: UIDynamicAnimator!
var dynamicItemBehavior: UIDynamicItemBehavior!
var bird1: UIView!
var plane1: UIView!
var collisionBehavior:UICollisionBehavior!
var score : Int = 500

func behaviorFunctions() {
    dynamicItemBehavior = UIDynamicItemBehavior(items: [bird1, plane1])
    collisionBehavior = UICollisionBehavior(items: [bird1, plane1])
    collisionBehavior.translatesReferenceBoundsIntoBoundary = true
    collisionBehavior.addBoundary(withIdentifier: "plane1" as NSCopying, for: UIBezierPath(rect: plane1.frame))
    collisionBehavior.addBoundary(withIdentifier: "bird1" as NSCopying, for: UIBezierPath(rect: bird1.frame));        animator.addBehavior(dynamicItemBehavior!)
    animator.addBehavior(collisionBehavior)


    collisionBehavior.action = {

      //  for _ in self.imageArrayBird!{
            if(self.plane1.frame.intersects(self.bird1.frame)){
                self.score = self.score - 50
                       print (self.score)
            }
        //}
    }
}



override func viewDidLoad() {
            super.viewDidLoad()
    animator = UIDynamicAnimator.init(referenceView: self.view)
}
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    bird1 = UIView.init(frame: CGRect.init(x: 100, y: 100, width: 100, height: 100))
    plane1 = UIView.init(frame: CGRect.init(x: 100, y: 150, width: 100, height: 100))
    bird1.backgroundColor = .red
    plane1.backgroundColor = .yellow
    self.view.addSubview(bird1)
    self.view.addSubview(plane1)
    behaviorFunctions()
}
}