(Swift)如何检测/记录collisionBehavior发生的次数?

时间:2017-03-01 21:06:17

标签: ios swift

我有一个简单的乒乓球比赛,到目前为止一切运作良好。但是,我想计算一下球击中"桨的次数"作为一种高分。这是sliderBar(划桨)触摸事件的代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !self.isBallRolling {
        let pushBehavior = UIPushBehavior(items: [self.ball], mode: .instantaneous)
        pushBehavior.magnitude = 1.5
        self.animator.addBehavior(pushBehavior)
        self.isBallRolling = true
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch: UITouch? = touches.first
    let touchLocation: CGPoint? = touch?.location(in: self.view)
    let yPoint: CGFloat = self.sliderBarCenterPoint.y
    let sliderBarCenter = CGPoint(x: CGFloat((touchLocation?.x)!), y: yPoint)
    self.sliderBar.center = sliderBarCenter
    self.animator.updateItem(usingCurrentState: self.sliderBar)
}

func collisionBehavior(_ behavior: UICollisionBehavior, beganContactFor item1: UIDynamicItem, with item2: UIDynamicItem, at p: CGPoint) {

    let pushBehavior = UIPushBehavior(items: [self.ball], mode: .instantaneous)
    pushBehavior.angle = 0.0
    pushBehavior.magnitude = 0.75
    self.animator.addBehavior(pushBehavior)
}



// The label that displays the score
let countLabel: UILabel = {
    let frame = CGRect(x: 100, y: 100, width: 200, height: 50)
    let cl = UILabel(frame: frame)
    cl.textAlignment = NSTextAlignment.center
    cl.text = ""
    cl.textColor = UIColor.red
    cl.translatesAutoresizingMaskIntoConstraints = false

    return cl
}()

func setupCountLabel() {
    countLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    countLabel.bottomAnchor.constraint(equalTo: self.sliderBar.topAnchor, constant: -3).isActive = true
    countLabel.widthAnchor.constraint(equalToConstant: 150).isActive = true
    countLabel.heightAnchor.constraint(equalToConstant: 73).isActive = true
}

我之前从未与UICollisionBehaviorDelegate合作过 - 我应该在哪里以及如何检测球击中sliderBar的次数?

感谢您的帮助!

0 个答案:

没有答案